Reputation: 107
I have read articles about GCM may refresh registration id with no regular cycle. I am trying to build an app using push notification but not so sure how to handle such refreshed registration ids.
My first strategy is requesting registration id everytime the app starts and send it to the app server. It looks working but sounds wrong somehow...
Is it ok to do like this?
Upvotes: 8
Views: 5881
Reputation: 1828
Registration refresh is not included in the new GCM library.
Words of Costin Manolache
The 'periodical' refresh never happened, and the registration refresh is not included in the new GCM library.
The only known cause for registration ID change is the old bug of apps getting unregistered automatically if they receive a message while getting upgraded. Until this bug is fixed apps still need to call register() after upgrade, and so far the registration ID may change in this case. Calling unregister() explicitly usually changes the registration ID too.
The suggestion/workaround is to generate your own random identifier, saved as a shared preference for example. On each app upgrade you can upload the identifier and the potentially new registration ID. This may also help tracking and debugging the upgrade and registration changes on server side.
Upvotes: 1
Reputation: 2205
Basically, you should do the following in your main activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, GCMIntentService.GCM_SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
}
Afterwards you should send the registration id to your app server, whenever the app receives an com.google.android.c2dm.intent.REGISTRATION
intent with a registration_id
extra. This could happen when Google periodically updates the app's id.
You can achieve this by extending com.google.android.gcm.GCMBaseIntentService
with your own implementation, e.g.:
public class GCMIntentService extends GCMBaseIntentService {
// Also known as the "project id".
public static final String GCM_SENDER_ID = "XXXXXXXXXXXXX";
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(GCM_SENDER_ID);
}
@Override
protected void onRegistered(Context context, String regId) {
// Send the regId to your server.
}
@Override
protected void onUnregistered(Context context, String regId) {
// Unregister the regId at your server.
}
@Override
protected void onMessage(Context context, Intent msg) {
// Handle the message.
}
@Override
protected void onError(Context context, String errorId) {
// Handle the error.
}
}
For more details, I would (re)read the documentation for writing the client side code and the Advanced Section of the GCM documentation.
Hope that helps!
Upvotes: 5