I have implemented GCM in my project using guidelines from https://developers.google.com.
Steps that I have take are:
For receiving device Token:
-> Class
GCMRegistrationIntentService
which extendsIntentService
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.
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).
Class
GCMTokenRefreshListenerService
which extendsInstanceIDListenerService
to get the token in case old one expired.-> In this I made a call to
GCMRegistrationIntentService
inonTokenRefresh()
Now my questions are:
- In which case GCMTokenRefreshListenerService be called?
- What is instanceID? What is lifecycle of instanceID?
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?
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?
- Do I have to call GCM every time when my app opens to get the token?
You don't have to call your
GCMTokenRefreshListenerService
it is called automatically by android system whenever your token is refreshed.Instance ID provides a unique ID per instance of your apps. You can find more about it here.
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 yourSharedPreference
you can do that from yourRegistrationService
once you have received your token.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 youronTokenRefresh()
method. You should than make your server aware of this new token to receive notifications properly using theRegistrationService
. And you don't have to open your app to get the refreshed token.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