com.google.android.gcm.GCMRegistrar Java Examples

The following examples show how to use com.google.android.gcm.GCMRegistrar. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PushMainActivity.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // this is a hack to force AsyncTask to be initialized on main thread. Without this things
  // won't work correctly on older versions of Android (2.2, apilevel=8)
  try {
  	Class.forName("android.os.AsyncTask");
  } catch (Exception ignored) {}
  
  GCMRegistrar.checkDevice(this);
  GCMRegistrar.checkManifest(this);

  initUI();

  AppServices.loginAndRegisterForPush(this);
}
 
Example #2
Source File: Util.java    From ownmdm with GNU General Public License v2.0 6 votes vote down vote up
public static void registerOnLocalServer(final Context context) {
	Util.logDebug("Registrando en servidor local");
    mRegisterTask = new AsyncTask<Void, Void, Void>() {

          @Override
          protected Void doInBackground(Void... params) {
              boolean registered = ServerUtilities.register(context, Util.regId, getModel(context));
              if (!registered) {
                  GCMRegistrar.unregister(context); 
              }
              return null;
          }

          @Override
          protected void onPostExecute(Void result) {
              mRegisterTask = null;
          }

      };
    mRegisterTask.execute(null, null, null);
}
 
Example #3
Source File: Util.java    From ownmdm with GNU General Public License v2.0 6 votes vote down vote up
/**
   * GCM
   */
  public static void setGCM(Context context) {
      //
      // GCM
      //
try {
       GCMRegistrar.checkDevice(context);
       GCMRegistrar.checkManifest(context);
       final String regId = GCMRegistrar.getRegistrationId(context);
       
       if (regId.equals("")) {
       	GCMRegistrar.register(context, Util.SENDER_ID);
       } else {
       	Util.regId = regId;
       	Util.logDebug("Already registered - imei: " + Util.imei + " gcm: " + regId);

       	Util.registradoGCM = true; // marcar como registrado para no intentarlo m�s

       	registerOnLocalServer(context); // lo hago otra vez para asegurar
       }
      
} catch (Exception e) {
	Util.logDebug("Exception setGCM: " + e.getMessage());
}
  	
  }
 
Example #4
Source File: ServerUtilities.java    From ownmdm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unregister this account/device pair within the server.
 */
static void unregister(final Context context, final String regId) {
    Util.logDebug("unregistering device (regId = " + regId + ")");
    String serverUrl = Util.SERVER_URL + "/mdm/unregister.php";
    Map<String, String> params = new HashMap<String, String>();
    params.put("regId", regId);
    params.put("key", Util.serverDataKey);
    
    try {
        post(serverUrl, params);
        GCMRegistrar.setRegisteredOnServer(context, false);
    } catch (IOException e) {
        // At this point the device is unregistered from GCM, but still
        // registered in the server.
        // We could try to unregister again, but it is not necessary:
        // if the server tries to send a message to the device, it will get
        // a "NotRegistered" error message and should unregister the device.
    }
}
 
Example #5
Source File: ServerUtilities.java    From Klyph with MIT License 6 votes vote down vote up
/**
 * Unregister this account/device pair within the server.
 */
public static void unregister(final Context context, final String regId)
{
	Log.i(TAG, "unregistering device (regId = " + regId + ")");
	
	Map<String, String> params = new HashMap<String, String>();
	params.put("regId", regId);
	
	try
	{
		post(UNREGISTER_URL, params);
		GCMRegistrar.setRegisteredOnServer(context, false);
		
		Log.d("ServerUtilities", context.getString(R.string.gcm_server_unregistered));
	}
	catch (IOException e)
	{
		// At this point the device is unregistered from GCM, but still
		// registered in the server.
		// We could try to unregister again, but it is not necessary:
		// if the server tries to send a message to the device, it will get
		// a "NotRegistered" error message and should unregister the device.
		Log.d("ServerUtilities", context.getString(R.string.gcm_server_unregister_error, e.getMessage()));
	}
}
 
Example #6
Source File: KlyphADM.java    From Klyph with MIT License 6 votes vote down vote up
@Override
protected Void doInBackground(Context... params)
{
	GCMRegistrar.unregister(params[0]);
	try
	{
	    Class.forName( "com.amazon.device.messaging.ADM" );
	}
	catch (ClassNotFoundException e)
	{
	    return null;
	}
	final ADM adm = new ADM(KlyphApplication.getInstance());
	adm.startUnregister();
	return null;
}
 
Example #7
Source File: MainActivity.java    From datmusic-android with Apache License 2.0 6 votes vote down vote up
/**
 * Registers GCM and sends to server
 */
private void registerGCM() {
    try {
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            GCMRegistrar.register(this, Config.GCM_SENDER_ID);
        } else {
            if (Remember.getBoolean("gcmSent", false)) {
                ApiService.getClientJackson().register(
                    regId,
                    U.getDeviceId(this)
                ).enqueue(new Summon<Result>() {
                    @Override
                    public void onSuccess(Call<Result> call, Response<Result> response) {
                        Remember.putBoolean("gcmSent", true);
                    }
                });
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #8
Source File: AndroidChannel.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the GCM registration ID associated with the channel. Checks the {@link GCMRegistrar}
 * unless {@link #setRegistrationIdForTest} has been called.
 */
String getRegistrationId() {
  String registrationId = (registrationIdForTest != null) ? registrationIdForTest :
      GCMRegistrar.getRegistrationId(context);

  // Callers check for null registration ID rather than "null or empty", so replace empty strings
  // with null here.
  if ("".equals(registrationId)) {
    registrationId = null;
  }
  return registrationId;
}
 
Example #9
Source File: AndroidMessageReceiverService.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Initializes GCM as a convenience method for tests. In production, applications should handle
 * this.
 */
public static void initializeGcmForTest(Context context, Logger logger, String senderId) {
  // Initialize GCM.
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.equals("")) {
    logger.info("Not registered with GCM; registering");
    GCMRegistrar.register(context, senderId);
  } else {
    logger.fine("Already registered with GCM: %s", regId);
  }
}
 
Example #10
Source File: AndroidMessageSenderService.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns the network id for this channel, or {@code null} if one cannot be determined. */


public static NetworkEndpointId getNetworkEndpointId(Context context, Logger logger) {
  String registrationId = GCMRegistrar.getRegistrationId(context);
  if (Strings.isNullOrEmpty(registrationId)) {
    // No registration with GCM; we cannot compute a network id. The GCM documentation says the
    // string is never null, but we'll be paranoid.
    logger.warning("No GCM registration id; cannot determine our network endpoint id: %s",
        registrationId);
    return null;
  }
  return CommonProtos2.newAndroidEndpointId(registrationId,
      NO_CLIENT_KEY, context.getPackageName(), AndroidChannelConstants.CHANNEL_VERSION);
}
 
Example #11
Source File: Client.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
public void registerPush(Context context) {
    final String regId = GCMRegistrar.getRegistrationId(context);
    if ("".equals(regId)) {
        GCMRegistrar.register(context, GCM_SENDER_ID);
    } else {
        if (GCMRegistrar.isRegisteredOnServer(context)) {
            Log.i(TAG, "Already registered with GCM");
        } else {
            this.registerPush(context, regId);
        }
    }
}
 
Example #12
Source File: MultiplexingGcmListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Registers with GCM if not already registered. Also verifies that the device supports GCM
 * and that the manifest is correctly configured. Returns the existing registration id, if one
 * exists, or the empty string if one does not.
 *
 * @throws UnsupportedOperationException if the device does not have all GCM dependencies
 * @throws IllegalStateException if the manifest is not correctly configured
 */
public static String initializeGcm(Context context) {
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  final String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.equals("")) {
    GCMRegistrar.register(context, readSenderIdsFromManifestOrDie(context));
  }
  return regId;
}
 
Example #13
Source File: MultiplexingGcmListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Registers with GCM if not already registered. Also verifies that the device supports GCM
 * and that the manifest is correctly configured. Returns the existing registration id, if one
 * exists, or the empty string if one does not.
 *
 * @throws UnsupportedOperationException if the device does not have all GCM dependencies
 * @throws IllegalStateException if the manifest is not correctly configured
 */
public static String initializeGcm(Context context) {
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  final String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.equals("")) {
    GCMRegistrar.register(context, readSenderIdsFromManifestOrDie(context));
  }
  return regId;
}
 
Example #14
Source File: AppServices.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
static void registerPush(Context context) {

    final String regId = GCMRegistrar.getRegistrationId(context);

    if ("".equals(regId)) {
      GCMRegistrar.register(context, Settings.GCM_SENDER_ID);
    } else {
      if (GCMRegistrar.isRegisteredOnServer(context)) {
        Log.i(TAG, "Already registered with GCM");
      } else {
        AppServices.register(context, regId);
      }
    }
  }
 
Example #15
Source File: Global.java    From Favorite-Android-Client with Apache License 2.0 5 votes vote down vote up
public static String GCMReg() {
	GCMRegistrar.checkDevice(mod);
	GCMRegistrar.checkManifest(mod);
	final String regId = GCMRegistrar.getRegistrationId(ModApplication
			.getInstance());
	if ("".equals(regId)) // 구글 가이드에는 regId.equals("")로 되어 있는데
							// Exception을 피하기 위해 수정
		GCMRegistrar.register(mod, "743824910564");

	return regId;

}
 
Example #16
Source File: PushManager.java    From divide with Apache License 2.0 5 votes vote down vote up
private void register4Push(){
    Context context = config.app;
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);
    final String regId = GCMRegistrar.getRegistrationId(context);
    if (regId.equals("")) {
        logger.info("Registering");
        GCMRegistrar.setRegisteredOnServer(context, true);
        GCMRegistrar.register(context, senderId);
    } else {
        logger.info("Push already registered: " + regId);
    }
}
 
Example #17
Source File: PushManager.java    From divide with Apache License 2.0 5 votes vote down vote up
public void setEnablePush(boolean enable, String senderId){
    if(enable){
        this.senderId = senderId;
        authManager.addLoginListener(loginListener);
    } else {
        if(loginListener != null) loginListener.unsubscribe();
        this.senderId = null;
        if(isRegistered(config.app)){
            unregister();
            GCMRegistrar.unregister(config.app);
        }
    }
    this.senderId = senderId;
}
 
Example #18
Source File: AndroidMessageSenderService.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns the network id for this channel, or {@code null} if one cannot be determined. */


public static NetworkEndpointId getNetworkEndpointId(Context context, Logger logger) {
  String registrationId = GCMRegistrar.getRegistrationId(context);
  if (Strings.isNullOrEmpty(registrationId)) {
    // No registration with GCM; we cannot compute a network id. The GCM documentation says the
    // string is never null, but we'll be paranoid.
    logger.warning("No GCM registration id; cannot determine our network endpoint id: %s",
        registrationId);
    return null;
  }
  return CommonProtos2.newAndroidEndpointId(registrationId,
      NO_CLIENT_KEY, context.getPackageName(), AndroidChannelConstants.CHANNEL_VERSION);
}
 
Example #19
Source File: AndroidMessageReceiverService.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Initializes GCM as a convenience method for tests. In production, applications should handle
 * this.
 */
public static void initializeGcmForTest(Context context, Logger logger, String senderId) {
  // Initialize GCM.
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.equals("")) {
    logger.info("Not registered with GCM; registering");
    GCMRegistrar.register(context, senderId);
  } else {
    logger.fine("Already registered with GCM: %s", regId);
  }
}
 
Example #20
Source File: AndroidChannel.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the GCM registration ID associated with the channel. Checks the {@link GCMRegistrar}
 * unless {@link #setRegistrationIdForTest} has been called.
 */
String getRegistrationId() {
  String registrationId = (registrationIdForTest != null) ? registrationIdForTest :
      GCMRegistrar.getRegistrationId(context);

  // Callers check for null registration ID rather than "null or empty", so replace empty strings
  // with null here.
  if ("".equals(registrationId)) {
    registrationId = null;
  }
  return registrationId;
}
 
Example #21
Source File: GCMIntentService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onUnregistered(Context context, String registrationId) {
    Util.logDebug("Device unregistered");
    if (GCMRegistrar.isRegisteredOnServer(context)) {
        ServerUtilities.unregister(context, registrationId);
    } else {
        // This callback results from the call to unregister made on
        // ServerUtilities when the registration to the server failed.
        Util.logDebug("Ignoring unregister callback");
    }
    
}
 
Example #22
Source File: CaffeinaGCMModule.java    From gcm with MIT License 5 votes vote down vote up
@Kroll.method
@SuppressWarnings("unchecked")
public void registerForPushNotifications(HashMap options) {
	String senderId = (String)options.get("senderId");

	successCallback = (KrollFunction)options.get("success");
	errorCallback = (KrollFunction)options.get("error");
	messageCallback = (KrollFunction)options.get("callback");

	if (senderId != null) {
		GCMRegistrar.register(TiApplication.getInstance(), senderId);
	} else {
		sendError("No GCM senderId specified; get it from the Google Play Developer Console");
	}
}
 
Example #23
Source File: AndroidMessageSenderService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/** Returns the network id for this channel, or {@code null} if one cannot be determined. */


public static NetworkEndpointId getNetworkEndpointId(Context context, Logger logger) {
  String registrationId;
  String clientKey;

  // Select the registration token to use.
  if (AndroidChannelPreferences.getGcmChannelType(context) == GcmChannelType.UPDATED) {
    registrationId = AndroidChannelPreferences.getRegistrationToken(context);
    clientKey = GcmSharedConstants.ANDROID_ENDPOINT_ID_CLIENT_KEY;
  } else {
    // No client key when using old style registration id.
    clientKey = "";
    try {
      registrationId = GCMRegistrar.getRegistrationId(context);
    } catch (RuntimeException exception) {
      // GCMRegistrar#getRegistrationId occasionally throws a runtime exception. Catching the
      // exception rather than crashing.
      logger.warning("Unable to get GCM registration id: %s", exception);
      registrationId = null;
    }
  }
  if ((registrationId == null) || registrationId.isEmpty()) {
    // No registration with GCM; we cannot compute a network id. The GCM documentation says the
    // string is never null, but we'll be paranoid.
    logger.warning(
        "No GCM registration id; cannot determine our network endpoint id: %s", registrationId);
    return null;
  }
  return CommonProtos.newAndroidEndpointId(registrationId, clientKey,
      context.getPackageName(), AndroidChannelConstants.CHANNEL_VERSION);
}
 
Example #24
Source File: AndroidMessageReceiverService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes GCM as a convenience method for tests. In production, applications should handle
 * this.
 */
public static void initializeGcmForTest(Context context, Logger logger, String senderId) {
  // Initialize GCM.
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.isEmpty()) {
    logger.info("Not registered with GCM; registering");
    GCMRegistrar.register(context, senderId);
  } else {
    logger.fine("Already registered with GCM: %s", regId);
  }
}
 
Example #25
Source File: KlyphGCM.java    From Klyph with MIT License 5 votes vote down vote up
public static void registerIfNecessary()
{
	final Context context = KlyphApplication.getInstance();
	
	try
	{
		GCMRegistrar.checkDevice(context);
	}
	catch (UnsupportedOperationException e)
	{
		return;
	}
	// GCMRegistrar.checkManifest(context);

	final String regId = KlyphPreferences.getGCMRegId();

	// Register GCM
	if (regId.length() == 0)
	{
		Log.d("KlyphGCM", "register GCM");

		registerTask = new RegisterTask();
		registerTask.execute(context);
	}
	else
	{
		// Register on server, maybe last attempt failed
		Log.d("KlyphGCM", "register on server");
			
		registerOnServerTask = new RegisterOnServerTask();
		registerOnServerTask.execute(context);
	}
}
 
Example #26
Source File: AuthenticationErrorActivity.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_authentication_error);
	Bundle extras = getIntent().getExtras();
	if (extras != null) {
		if (extras.containsKey(getResources().getString(R.string.intent_extra_regid))) {
			registrationId =
					extras.getString(getResources().getString(R.string.intent_extra_regid));
		}

		if (extras.containsKey(getResources().getString(R.string.intent_extra_from_activity))) {
			fromActivity =
					extras.getString(
							getResources().getString(R.string.intent_extra_from_activity));
		}
	}
	
	if (registrationId == null || registrationId.isEmpty()) {
		registrationId = GCMRegistrar.getRegistrationId(this);
	}
	
	txtMessage = (TextView) findViewById(R.id.error);

	btnTryAgain = (Button) findViewById(R.id.btnTryAgain);
	btnTryAgain.setTag(TAG_BTN_TRY_AGAIN);
	btnTryAgain.setOnClickListener(onClickListener_BUTTON_CLICKED);

	if (fromActivity.equals(RegistrationActivity.class.getSimpleName())) {
		txtMessage.setText(getResources().getString(R.string.error_registration_failed));
	} else if (fromActivity.equals(AlreadyRegisteredActivity.class.getSimpleName())) {
		txtMessage.setText(getResources().getString(R.string.error_unregistration_failed));
		btnTryAgain.setTag(TAG_BTN_UNREGISTER);
	}

}
 
Example #27
Source File: MultiplexingGcmListener.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Registers with GCM if not already registered. Also verifies that the device supports GCM
 * and that the manifest is correctly configured. Returns the existing registration id, if one
 * exists, or the empty string if one does not.
 *
 * @throws UnsupportedOperationException if the device does not have all GCM dependencies
 * @throws IllegalStateException if the manifest is not correctly configured
 */
public static String initializeGcm(Context context) {
  AndroidChannelPreferences.setGcmChannelType(context, GcmChannelType.DEFAULT);
  GCMRegistrar.checkDevice(context);
  GCMRegistrar.checkManifest(context);
  final String regId = GCMRegistrar.getRegistrationId(context);
  if (regId.isEmpty()) {
    GCMRegistrar.register(context, readSenderIdsFromManifestOrDie(context));
  }
  return regId;
}
 
Example #28
Source File: GCMModule.java    From gcmpush with Apache License 2.0 5 votes vote down vote up
@Kroll.method
@SuppressWarnings("unchecked")
public void registerPush(HashMap options) {

    Log.d(LCAT, "registerPush called");

    String senderId = (String) options.get("senderId");
    Map<String, Object> notificationSettings = (Map<String, Object>) options.get("notificationSettings");
    successCallback = (KrollFunction) options.get("success");
    errorCallback = (KrollFunction) options.get("error");
    messageCallback = (KrollFunction) options.get("callback");

    /* Store notification settings in global Ti.App properties */
    JSONObject json = new JSONObject(notificationSettings);
    TiApplication.getInstance().getAppProperties().setString(GCMModule.NOTIFICATION_SETTINGS, json.toString());

    if (senderId != null) {
        GCMRegistrar.register(TiApplication.getInstance(), senderId);

        String registrationId = getRegistrationId();
        if (registrationId != null && registrationId.length() > 0) {
            sendSuccess(registrationId);
        }
    } else {
        sendError(errorCallback, "No GCM senderId specified; get it from the Google Play Developer Console");
    }
}
 
Example #29
Source File: GCMModule.java    From gcmpush with Apache License 2.0 5 votes vote down vote up
@Kroll.method
public void unregister() {
    Log.d(LCAT, "unregister called (" + (instance != null) + ")");
    try {
        GCMRegistrar.unregister(TiApplication.getInstance());
    } catch (Exception ex) {
        Log.e(LCAT, "Cannot unregister from push: " + ex.getMessage());
    }
}
 
Example #30
Source File: ServerUtilities.java    From Klyph with MIT License 4 votes vote down vote up
/**
 * Register this account/device pair within the server.
 * 
 */
public static boolean register(final Context context, final String regId)
{
	Log.i(TAG, "registering device (regId = " + regId + ")");

	Map<String, String> params = new HashMap<String, String>();
	params.put("regId", regId);
	params.put("facebook_user_id", KlyphSession.getSessionUserId());
	params.put("udid", Android.getDeviceUDID(context));
	
	long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
	
	// Once GCM returns a registration id, we need to register on our server
	// As the server might be down, we will retry it a couple
	// times.
	for (int i = 1; i <= MAX_ATTEMPTS; i++)
	{
		Log.d(TAG, "Attempt #" + i + " to register");
		
		try
		{
			Log.d("ServerUtilities", context.getString(R.string.gcm_server_registering, i, MAX_ATTEMPTS));
			
			post(REGISTER_URL, params);
			GCMRegistrar.setRegisteredOnServer(context, true);
			
			Log.d("ServerUtilities", context.getString(R.string.gcm_server_registered));
			
			return true;
		}
		catch (IOException e)
		{
			// Here we are simplifying and retrying on any error; in a real
			// application, it should retry only on unrecoverable errors
			// (like HTTP error code 503).
			Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
			if (i == MAX_ATTEMPTS)
			{
				Log.e(TAG, "Max attempt reached, giving up registration on server");
				GCMRegistrar.setRegisteredOnServer(context, false);
				break;
			}
			try
			{
				Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
				Thread.sleep(backoff);
			}
			catch (InterruptedException e1)
			{
				// Activity finished before we complete - exit.
				Log.d(TAG, "Thread interrupted: abort remaining retries!");
				Thread.currentThread().interrupt();
				GCMRegistrar.setRegisteredOnServer(context, false);
				return false;
			}
			// increase backoff exponentially
			backoff *= 2;
		}
	}
	
	Log.d("ServerUtilities", context.getString(R.string.gcm_server_register_error, MAX_ATTEMPTS));
	
	return false;
}