Java Code Examples for com.google.android.gms.iid.InstanceID#getToken()

The following examples show how to use com.google.android.gms.iid.InstanceID#getToken() . 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: RegistrationIntentService.java    From mattermost-android-classic with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    try {
        synchronized (TAG) {
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_sender_id),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.d(TAG, "GCM registration token: " + token);

            sharedPreferences.edit().putString("device_id", token).apply();
        }
    } catch (IOException e) {
        Log.d(TAG, "Failed to complete token refresh", e);
    }
    Intent registrationComplete = new Intent(RegistrationConstants.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 2
Source File: IIDService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
public static void getToken(Context context, boolean refresh) {
    try {
        // Get token
        InstanceID instanceID = InstanceID.getInstance(context);
        String token = instanceID.getToken(
                context.getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        Log.i(TAG, "Token=" + token);

        // Store token
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs.edit().putString(SettingsFragment.PREF_GCM_TOKEN, token).apply();

        // Subscribe to topics
        GcmService.subscribeBroadcasts(context);
        GcmService.subscribeWeatherUpdates(context);
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}
 
Example 3
Source File: RegistrationIntentService.java    From Advanced_Android_Development with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {
        // In the (unlikely) event that multiple refresh operations occur simultaneously,
        // ensure that they are processed sequentially.
        synchronized (TAG) {
            // Initially this call goes out to the network to retrieve the token, subsequent calls
            // are local.
            InstanceID instanceID = InstanceID.getInstance(this);

            // TODO: gcm_default sender ID comes from the API console
            String senderId = getString(R.string.gcm_defaultSenderId);
            if ( senderId.length() != 0 ) {
                String token = instanceID.getToken(senderId,
                        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                sendRegistrationToServer(token);
            }

            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(MainActivity.SENT_TOKEN_TO_SERVER, true).apply();
        }
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);

        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(MainActivity.SENT_TOKEN_TO_SERVER, false).apply();
    }
}
 
Example 4
Source File: GPPRegistrationIntentService.java    From GCMPushPlugin with MIT License 5 votes vote down vote up
@Override
    protected void onHandleIntent(Intent intent) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        try {
            // In the (unlikely) event that multiple refresh operations occur simultaneously,
            // ensure that they are processed sequentially.
            synchronized (TAG) {
                // [START register_for_gcm]
                // Initially this call goes out to the network to retrieve the token, subsequent calls
                // are local.
                // [START get_token]

                final String projectId = intent.getExtras().getString(GCMPushPlugin.SENDER_ID_KEY);
                InstanceID instanceID = InstanceID.getInstance(this);
                String token = instanceID.getToken(projectId,
                        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                // [END get_token]
//                Log.i(TAG, "GCM Registration Token: " + token);

                // You should store a boolean that indicates whether the generated token has been
                // sent to your server. If the boolean is false, send the token to your server,
                // otherwise your server should have already received the token.
                sharedPreferences.edit().putBoolean(GCMPushPlugin.SENT_TOKEN_KEY, true).apply();
                sharedPreferences.edit().putString(GCMPushPlugin.GCM_TOKEN_KEY, token).apply();
                // [END register_for_gcm]
            }
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
            sharedPreferences.edit().putBoolean(GCMPushPlugin.SENT_TOKEN_KEY, false).apply();
        }
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(GCMPushPlugin.REG_COMPLETE_BROADCAST_KEY);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
 
Example 5
Source File: IDRegisterService.java    From easygoogle with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    String senderId = intent.getStringExtra(MessagingFragment.SENDER_ID_ARG);
    String gcmPermissionName = intent.getStringExtra(MessagingFragment.GCM_PERMISSION_ARG);

    try {
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        Log.i(TAG, "GCM Registration Token: " + token);

        // Find any services that could handle this
        List<ComponentName> services = GCMUtils.findServices(this, gcmPermissionName);

        // Notify the services of a new token
        for (ComponentName cn : services) {
            Log.d(TAG, "Launching service: " + cn);

            Intent newTokenIntent = new Intent();
            newTokenIntent.setComponent(cn);
            newTokenIntent.setAction(getString(R.string.action_new_token));
            newTokenIntent.putExtra(EasyMessageService.EXTRA_TOKEN, token);

            startService(newTokenIntent);
        }
    } catch (Exception e) {
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        Log.e(TAG, "Failed to complete token refresh", e);
    }
}
 
Example 6
Source File: GCMRegistration.java    From redalert-android with Apache License 2.0 5 votes vote down vote up
public static void registerForPushNotifications(Context context) throws Exception {
    // Make sure we have Google Play Services
    if (!GooglePlayServices.isAvailable(context)) {
        // Throw exception
        throw new Exception(context.getString(R.string.noGooglePlayServices));
    }

    // Get instance ID API
    InstanceID instanceID = InstanceID.getInstance(context);

    // Get a GCM registration token
    String token = instanceID.getToken(GCMGateway.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

    // Log to logcat
    Log.d(Logging.TAG, "GCM registration success: " + token);

    // Get GCM PubSub handler
    GcmPubSub pubSub = GcmPubSub.getInstance(context);

    // Subscribe to alerts topic
    // (limited to 1M subscriptions app-wide - think about how to scale this when the time comes)
    pubSub.subscribe(token, GCMGateway.ALERTS_TOPIC, null);

    // Log it
    Log.d(Logging.TAG, "GCM subscription success: " + GCMGateway.ALERTS_TOPIC);

    // Prepare an object to store and send the registration token to our API
    RegistrationRequest register = new RegistrationRequest(token, API.PLATFORM_IDENTIFIER);

    // Send the request to our API
    HTTP.post(API.API_ENDPOINT + "/register", Singleton.getJackson().writeValueAsString(register));

    // Persist it locally
    saveRegistrationToken(context, token);
}
 
Example 7
Source File: GCMModule.java    From gcmpush with Apache License 2.0 5 votes vote down vote up
public String getToken(String senderId){
    // get token and return it
    try {
        InstanceID instanceID = InstanceID.getInstance(TiApplication.getInstance());
        return instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    } catch (Exception ex) {
        return null;
    }
}
 
Example 8
Source File: RegistrationIntentService.java    From google-services with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
        // See https://developers.google.com/cloud-messaging/android/start for details on this file.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        Log.i(TAG, "GCM Registration Token: " + token);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        // Subscribe to topic channels
        subscribeTopics(token);

        // You should store a boolean that indicates whether the generated token has been
        // sent to your server. If the boolean is false, send the token to your server,
        // otherwise your server should have already received the token.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 9
Source File: RegistrationIntentService.java    From friendlyping with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    try {
        // Just in case that onHandleIntent has been triggered several times in short
        // succession.
        synchronized (TAG) {
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.d(TAG, "GCM registration token: " + token);

            // Register to the server and subscribe to the topic of interest.
            sendRegistrationToServer(token);
            // The list of topics we can subscribe to is being implemented within the server.
            GcmPubSub.getInstance(this).subscribe(token, "/topics/newclient", null);

            final SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean(RegistrationConstants.SENT_TOKEN_TO_SERVER, true);
            editor.putString(RegistrationConstants.TOKEN, token);
            editor.apply();
        }
    } catch (IOException e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        sharedPreferences.edit().putBoolean(RegistrationConstants.
                SENT_TOKEN_TO_SERVER, false).apply();

    }
    Intent registrationComplete = new Intent(RegistrationConstants.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 10
Source File: RNPushNotificationRegistrationService.java    From react-native-push-notification-CE with MIT License 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    try {
        String SenderID = intent.getStringExtra("senderID");
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(SenderID,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        sendRegistrationToken(token);
    } catch (Exception e) {
        Log.e(LOG_TAG, TAG + " failed to process intent " + intent, e);
    }
}
 
Example 11
Source File: MyRegistrationIntentService.java    From openshop.io-android with MIT License 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    try {
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
        // See https://developers.google.com/cloud-messaging/android/start for details on this file.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]
        Timber.d("GCM token obtained: %s", token);

        // Send token to third party only if not already registered.
        if (!SettingsMy.getTokenSentToServer()) {
            boolean success = sendRegistrationToServer(token);

            // Subscribe to topic channels. Not implemented now.
            subscribeTopics(token);

            // You should store a boolean that indicates whether the generated token has been
            // sent to your server. If the boolean is false, send the token to your server,
            // otherwise your server should have already received the token.
            SettingsMy.setTokenSentToServer(success);
        }
        // [END register_for_gcm]
    } catch (Exception e) {
        Timber.e(e, "Failed to complete token refresh");
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        SettingsMy.setTokenSentToServer(false);
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(SettingsMy.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 12
Source File: GetGcmServerToken.java    From RxGcm with Apache License 2.0 5 votes vote down vote up
String retrieve(Context context) throws Exception {
    int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);

    if(status != ConnectionResult.SUCCESS) throw new RuntimeException(Constants.GOOGLE_PLAY_SERVICES_ERROR);

    InstanceID instanceID = InstanceID.getInstance(context);
    return instanceID.getToken(context.getString(R.string.gcm_defaultSenderId),
            GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
}
 
Example 13
Source File: GCMRegistrationIntentService.java    From pusher-websocket-android with MIT License 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {

    final InstanceID instanceID = InstanceID.getInstance(this);
    final String defaultSenderId = intent.getStringExtra("gcm_defaultSenderId");

    Intent gcmCalled = new Intent(PushNotificationRegistration.GCM_CALLED_INTENT_FILTER);
    int retryAttempts = 0;
    String token = null;

    while (token == null && retryAttempts < INSTANCE_ID_RETRY_ATTEMPTS){
        try {
            token = instanceID.getToken(defaultSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        }
        catch (IOException e) {
            Log.d(TAG, "Failed to get token from InstanceID", e);
        }
        finally {
            retryAttempts++;
        }
    }

    if(token == null){
        Log.e(TAG, "Failed to get token after " + INSTANCE_ID_RETRY_ATTEMPTS + " attempts.");
    }

    gcmCalled.putExtra(PushNotificationRegistration.TOKEN_EXTRA_KEY, token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(gcmCalled);
}
 
Example 14
Source File: RegistrationIntentService.java    From gcm-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Register for token for the specified sender Id
 *
 * @param instanceID instance of {@link InstanceID} associated with the sender Id
 * @param senderId Sender ID for which the token has to be deleted
 */
private String registerForToken(InstanceID instanceID, String senderId) throws IOException {
  String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
  if(GcmHelper.DEBUG_ENABLED)Log.i(GcmHelper.TAG, "PushRegistrationService: GCM Registration Token: " + token);
  //Notify the helper that the push token has been updated
  GcmHelper.getInstance().tokenUpdated(getApplicationContext(), token);
  return token;
}
 
Example 15
Source File: RegistrationIntentService.java    From newsApp with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
  SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

  try {
    // [START register_for_gcm]
    // Initially this call goes out to the network to retrieve the token, subsequent calls
    // are local.
    // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
    // See https://developers.google.com/cloud-messaging/android/start for details on this file.
    // [START get_token]
    InstanceID instanceID = InstanceID.getInstance(this);
    String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    // [END get_token]
    Log.i(TAG, "GCM Registration Token: " + token);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(token);

    // Subscribe to topic channels
    subscribeTopics(token);

    // You should store a boolean that indicates whether the generated token has been
    // sent to your server. If the boolean is false, send the token to your server,
    // otherwise your server should have already received the token.
    sharedPreferences.edit().putBoolean(com.ghn.android.QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
    // [END register_for_gcm]
  } catch (Exception e) {
    Log.d(TAG, "Failed to complete token refresh", e);
    // If an exception happens while fetching the new token or updating our registration data
    // on a third-party server, this ensures that we'll attempt the update at a later time.
    sharedPreferences.edit().putBoolean(com.ghn.android.QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
  }
  // Notify UI that registration has completed, so the progress indicator can be hidden.
  Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
  LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 16
Source File: TokenRetriever.java    From ello-android with MIT License 5 votes vote down vote up
public String getToken() {
    try {
        InstanceID instanceID = InstanceID.getInstance(context);
        String token = instanceID.getToken(context.getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        Log.d(TAG, "GCM Registration Token: " + token);
        return token;
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        return null;
    }
}
 
Example 17
Source File: PubSubService.java    From easygoogle with Apache License 2.0 4 votes vote down vote up
private String getToken(String senderId) throws IOException {
    InstanceID instanceID = InstanceID.getInstance(this);
    return instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
}