Home » Android » android – Google Cloud Messaging register method fails with IOException (MAIN_THREAD)

android – Google Cloud Messaging register method fails with IOException (MAIN_THREAD)

Posted by: admin June 15, 2020 Leave a comment

Questions:

Followed Google’s GCM example extremely carefully, but still came up with frustrating errors. Didn’t find the answer here, so thought I’d document it for future reference.

I was fairly sure that I had the manifest properly set up with the correct permissions etc (following the above example to the letter)… but this code always caused an IOException with the explanation “MAIN_THREAD”.

String regid = "";
try {
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
    String sender_id = getResources().getString(R.string.GCM_sender_id);
    regid = gcm.register(sender_id);
    Log.d(TAG, "Device registered, registration id=" + regid);
} 
catch (IOException ex) {
    Log.e(TAG, "Device registration failed", ex);
}

I was trying to find the problem by stepping through, so of course executed this code on the main thread. In retrospect the answer is obvious… but I’ll enter it below.

How to&Answers:

Drum roll… you can’t call the register method on the main thread. Obvious in retrospect, but perhaps there are others that suck as much as I do (but less each day!)

Answer:

call the register method in AsyncTask (doInBackGround)