Not receiving Notification when device token is updated in the background

553 views Asked by At

I have implemented GCM in my project using guidelines from https://developers.google.com.

Steps that I have take are:

  1. For receiving device Token:

    -> Class GCMRegistrationIntentService which extends IntentService and it is started from my mainActivity.

    -> In this service I have used:

    InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
    token = instanceID.getToken(AppConstants.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    

    I have received the token successfully.

  2. LocalBroadcastListener in my main activity to get the token generated in step 1 and store it in shared preference (Also send it to my message Server).

  3. Class GCMTokenRefreshListenerService which extends InstanceIDListenerService to get the token in case old one expired.

    -> In this I made a call to GCMRegistrationIntentService in onTokenRefresh()

Now my questions are:

  1. In which case GCMTokenRefreshListenerService be called?
  2. What is instanceID? What is lifecycle of instanceID?
  3. I ran the service from terminal using:

    ./adb shell am startservice -a com.google.android.gms.iid.InstanceID --es "CMD" "RST" -n package.name/service.name.
    

    Which gave me new token every time. How do I save this newly generated token in my shared preference?

  4. When I receive new token from this service, I don’t receive notification as my token is changed. I will have to open my app in order to update the token. How to update this token?

  5. Do I have to call GCM every time when my app opens to get the token?
1

There are 1 answers

0
Nitin Joshi On
  1. You don't have to call your GCMTokenRefreshListenerService it is called automatically by android system whenever your token is refreshed.

  2. Instance ID provides a unique ID per instance of your apps. You can find more about it here.

  3. First you don't have to run your service, as i said earlier it will be called automatically every time your token is refreshed. To send the token to your server you should call a separate service say RegistrationService. To save the token in your SharedPreference you can do that from your RegistrationService once you have received your token.

  4. You won't receive notification in your GcmListenerService this service is called only if your server has send some data to you via the push notification. Whenever your token is changed/refreshed you get a call in your onTokenRefresh() method. You should than make your server aware of this new token to receive notifications properly using the RegistrationService. And you don't have to open your app to get the refreshed token.

  5. No you don't have to call or start any of the service required for push notification you just have to specify the service properly in your manifest rest all things will be handled by android system