0
votes

In the docs for Google Cloud Messaging, Google says, "Do not call this method in the main thread; instead, use a service that extends IntentService"

Previously, when I was using gcm.register (now deprecated), I put my code inside an aSyncTask.

private void getRegId(final ArrayList<String> studentIds){
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String RegID;
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                    }
                    RegID = gcm.register(getVal("GCMProject"));
                } catch (IOException ex) {
                    RegID = "," + ex.getMessage();
                }
                return RegID;
            }

            @Override
            protected void onPostExecute(final String RegID) {
                String action = "SaveGCMRegID";
                if (RegID.charAt(0) == ',') {  //Error Message
                    action = "GCM Reg Error";
                } else {
                    KVDB.StoreValue("GCMRegID", RegID);
                }
            }
        }.execute(null, null, null);
    }

What does the IntentService do instead? I understand not waiting for a response on the main thread, but aSyncTask should do the trick, right? (I believe this question is different from Is there any reason to continue using IntentService for handling GCM messages?, which focuses on getting the work off the main thread)

1

1 Answers

2
votes

What does the IntentService do instead?

It makes your work more likely to finish before Android terminates your process.

I understand not waiting for a response on the main thread, but aSyncTask should do the trick, right?

AsyncTask, or a regular Thread, will get the work off of the main application thread. But a GCM message arrives in the form of a "broadcast" Intent. Once onReceive() returns, unless you happen to have the foreground from a UI standpoint, your process is eligible to be terminated to free up system RAM. If there's no running component in your process, you are likely to be terminated very quickly, perhaps within milliseconds. Using an IntentService is your app telling Android "I'm walkin' here!", so Android will be less likely to terminate your process. Yet, the IntentService itself stops as soon as onHandleIntent() returns, so once your work is done, Android can safely get rid of your process.