androidgoogle-cloud-messagingsender-id

Dynamically setting SENDER_ID in GCM


I am trying to set the project sender id dynamically by fetching it from a server but it throws the invalid sender id exception. I am fetching the sender id from server in the base Application class to make sure i get it before the application launches and i have also overrided the getSenderIds() method in GCMIntentService.

    public GCMIntentService() {  
        super();
    }

    @Override
    protected String[] getSenderIds(Context context) {
         String[] ids = new String[1];
         ids[0] = SENDER_ID;
         return ids;
    }  

But i am getting the invalid sender id exception. I'd would really appreciate if some one could give me an informed opinion on how to set the sender id dynammically from a server.


Solution

  • Ok i managed to do it my self. I'll try to explain it. So, firstly i edited the getSenderIds() method like this:

         @Override
        protected String[] getSenderIds(Context context) {
    
                updateSenderIdTask(context);
                String[] ids = new String[1];
                ids[0] = getSenderId(context);
                return ids;
        }  
    

    Previously i had set the ids[0] to a variable SENDER_ID that i would set inside the updateSenderIdTask method. The invalid sender id exception was thrown because GCM would access the SENDER_ID variable before the updateSenderIdTask method would get executed even though i had called it inside the base application class. So, i called the updateSenderTask inside the getSenderIds overrided method to make sure i fetch the id from server before GCM uses it. To double check it, i set the ids[0] to a local method getSenderId. Here is the implementation for it:

        static String getSenderId(Context context) {
    
                CustomSharedPrefs prefs = CustomSharedPrefs.getInstance(context);
                if (prefs.getString(Constants.SENDER_ID).equals("0")
                        || prefs.getString(Constants.SENDER_ID) == null) {
                    updateSenderIdTask(context);
                }
                Log.e("returned sender_id", prefs.getString(Constants.SENDER_ID));
                return prefs.getString(Constants.SENDER_ID);
    
    }  
    

    The updateSenderIdTask method fetches the id from server and stores it in a shared preference variable.