How to check if a google user account has been added on the device before starting the GCM procedure?

Is there a way to check if a user has added his google account on his device before starting the GCM API 8 registration procedure?

When you try to register without it, the application unexpectedly stops when you close it, therefore, to check first, warn the user and close the application.

+7
source share
3 answers

I looked at the source for checkDevice (), and as far as I can see, it only checks the API level and that the gcm package is on the device. Therefore, following CommonsWare recommendations, this code works for me:

private boolean deviceHasGoogleAccount(){ AccountManager accMan = AccountManager.get(this); Account[] accArray = accMan.getAccountsByType("com.google"); return accArray.length >= 1 ? true : false; } 

You will need a string

  <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 

in manifest

+16
source

You need to check the response received from GCM, if you get ACCOUNT_MISSING, you can handle this error.

In your GCMIntentService Class you have methods like onRegistered() onUnregistered() onMessage() onError() , in your onError() method

 /** * Method called on Error * */ @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); // HANDLE IF GCM SERVER SENT ERROR MESSAGES.! } 

enter image description here

For more information on error handling, check the Documentation.

+3
source

On the question of how to catch the exception:

 try { GCMRegistrar.checkDevice(context); System.out.println("Device has GCM capabilities. So registering for GCM"); //// write code here to register for GCM } catch(Exception e) { System.out.println("Cannot cregister for GCM"); } 

This is the logic to throw exceptions. Therefore, if any exception is thrown partially after the attempt, then the code partially after catch will be executed. checkDevice () throws an exception. If you do not catch the exception, the application will fail.

Also I don't think the syntax is all right, but this code will give you an idea of ​​what to do.

0
source

All Articles