GCM sender id not set on constructor solution

In an Android application that imports the Google Cloud Messaging library to receive messages from its server, it is possible to get the following exception:

FATAL EXCEPTION: IntentService[GCMIntentService-DynamicSenderIds-3]
java.lang.IllegalStateException: sender id not set on constructor
at com.google.android.gcm.GCMBaseIntentService.getSenderIds
(GCMBaseIntentService.java:125)
at com.google.android.gcm.GCMBaseIntentService.onHandleIntent
(GCMBaseIntentService.java:237)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.os.HandlerThread.run(HandlerThread.java:60)

 

This exception is thrown by some methods of the class “com.google.android.gcm.GCMBaseIntentService” when no sender id can be found and we are using the default constructor.

The solution is to override the “getSenderIds” method in our GCMIntentService class which should extend GCMBaseIntentService. This step is not included in the official GCM implementation guide but the default constructor’s javadoc explains:

Constructor that does not set a sender id, useful when the sender id is context-specific.
When using this constructor, the subclass must override getSenderIds(Context), otherwise methods such as onHandleIntent(Intent) will throw an IllegalStateException on runtime.

The overrided “getSenderIds” method should be something like this:

public class GCMIntentService extends GCMBaseIntentService {

  ...

  /**
  * Gets the sender ids.
  *
  *
By default, it returns the sender ids passed in
  * the constructor, but it could be overridden to
  * provide a dynamic sender id.
  *
  * @throws IllegalStateException if sender id was
  * not set on constructor.
  */
  @Override
  protected String[] getSenderIds(Context context) {
     String[] ids = new String[1];
     ids[0] = SENDER_ID;
     return ids;
  }

  ...
}
Share Button

2 Comments

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.