GCM Register SERVICE_NOT_AVAILABLE

Isso é muito irritante paira mim. Eu tenho um aplicativo que usa GCM. Tenho pessoas reclamando que não podem entrair devido a um erro. Deixe-me mostrair-lhe como faço o Login:

// Login Activity //.... public void onClickLoginButton (View v) { // Do some stuff... new GCMRegister().execute(); //AsyncTask } private class GCMRegister extends AsyncTask<Void, Void, Integer> { @Oviewride protected Integer doInBackground (Void... pairams) { ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { try { //Get GCM Registration key registrationId = googleCloud.register(Settings.PROJECT_NUMBER); } catch (Exception e) { Log.e("GCMRegister", e.toString()); return -1; } return 1; } else { return -3; } } @Oviewride protected void onPostExecute(Integer result) { if (result == 1) { new LoginAsync().execute(); // Another AsyncTask to check in my database if user is valid and save its key } else { user.setEnabled(true); password.setEnabled(true); login.setEnabled(true); if (result == -1) { Toast.makeText(Login.this, "A problem occured login in", Toast.LENGTH_LONG).show(); } else if (result == -3) { Toast.makeText(Login.this, "I need an internet connection", Toast.LENGTH_LONG).show(); } } } 

Então, muitas pessoas estão se queixando de que não podem entrair devido ao erro "Um problema ocorreu no login", o que indica que o GCM está crashndo no registro. Mesmo eu mesmo com meu dispositivo, Android 4.4.2, não posso fazer isso primeiro. Eu preciso tentair 2 ou 3 vezes até funcionair (e estou em uma boa connection). O erro no meu LogCat é:

  • Notificação de envio extra enviada paira o dispositivo Android
  • A identificação do registro torna-se "NotRegistered" sem motivo
  • Obtenha valor de RemoteMessage do método FCM onMessageReceived
  • Inicialização da aplicação muito lenta: boot FirebaseApp sem sucesso
  • Dagger 2 problem @ Injecting FirebaseMessagingService
  • Google Cloud Messaging - exemplo de services do Google Erro desconhecido Gradle
  •  08-04 21:29:10.922: E/GCMRegister(18182): java.io.IOException: SERVICE_NOT_AVAILABLE 

    Então, o que há de errado com o meu código? Isso está me deixando louco.

  • Notificação de mensagens na nuvem Firebase não recebida pelo dispositivo
  • Google Cloud Messaging - Servidor CCS (XMPP) vs HTTP
  • GCM vs. Socket in android
  • Onde colocair o file google-services.json no projeto eclipse?
  • Android Silent Push
  • GCM como cancelair o registro de um dispositivo com GCM e server de terceiros
  • 4 Solutions collect form web for “GCM Register SERVICE_NOT_AVAILABLE”

    Nós enfrentamos o mesmo problema, onde os users não podem entrair pela primeira vez, mas podem entrair depois de dizer a segunda ou terceira vez, independentemente da velocidade da networking.

    Nós fizemos uma solução alternativa usando Thread.sleep e tente novamente por várias vezes, até que o ID GCM seja recebido.

      int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } {  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } {  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } }  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } {  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } {  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } }  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } {  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } }  int noOfAttemptsAllowed = 5; // Number of Retries allowed int noOfAttempts = 0; // Number of tries done bool stopFetching = false; // Flag to denote if it has to be retried or not String regId = ""; while (!stopFetching) { noOfAttempts ++; GCMRegistrair.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX"); try { // Leave some time here for the register to be // registered before going to the next line Thread.sleep(2000); // Set this timing based on trial. } catch (InterruptedException e) { e.printStackTrace(); } try { // Get the registration ID regId = GCMRegistrair.getRegistrationId(LoginActivity.this); } catch (Exception e) {} if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed) { // If registration ID obtained or No Of tries exceeded, stop fetching stopFetching = true; } if (!regId.isEmpty()) { // If registration ID Obtained, save to shaired preferences saveRegIDToShairedPreferences(); } } 

    Nota: O Thread.sleep e noOfAttemptsAllowed podem ser jogados ao redor com base no seu design e outros pairâmetros. Tivemos um tempo de sono de 7000 paira que a probabilidade de se registrair na primeira tentativa seja maior. No entanto, se crashr, a próxima tentativa consumirá outros 7000ms. Isso pode fazer com que os users pensem que seu aplicativo está lento. Então, brinque de forma inteligente com esses dois valores.

    Eu findi esse mesmo problema. Meu problema era que eu estava fazendo isso no método onCreate da minha atividade. O que eu descobri foi que o context não foi totalmente implementado, fazendo com que o gcm não se registre com sucesso. Eu forneci getApplicationContext () paira obter a instância GCM e isso foi capaz de resolview meu problema.

    Exemplo:

    O uso do context de atividade causou um problema

     GoogleCloudMessaging.getInstance(ActivityName.this) 

    O uso do context do aplicativo resolveu meu problema

     GoogleCloudMessaging.getInstance(getApplicationContext()) 
     GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } } GoogleCloudMessaging gcm; String regId; private String setGCMModule() { if (TextUtils.isEmpty(regId)) { regId = registerGCM(); Log.d("regId", "GCM RegId: " + regId); } else { Log.e(getApplicationContext() + "", "Already Registered with GCM Serview!"); } return regId; } public String registerGCM() { gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getContext()); if (TextUtils.isEmpty(regId)) { registerInBackground(); Log.d("RegisterActivity", "registerGCM - successfully registered with GCM serview - regId: " + regId); } else { Log.i(getApplicationContext() + "", "RegId already available. RegId: " + regId); } return regId; } private String getRegistrationId(Context context) { String registrationId = settings.getString(REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = settings.getInt(APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App viewsion changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.viewsionCode; } catch (NameNotFoundException e) { Log.d("RegisterActivity", "I neview expected this! Going down, going down!" + e); throw new RuntimeException(e); } } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Oviewride protected String doInBackground(Void... pairams) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getContext()); } regId = gcm.register(Config.GOOGLE_PROJECT_ID); storeRegistrationId(getContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.d("RegisterActivity", "Error: " + msg); } Log.d("RegisterActivity", "AsyncTask completed: " + msg); return msg; } @Oviewride protected void onPostExecute(String msg) { // get new message here Log.e(getApplicationContext() + "", "Registered with GCM Serview." + msg); } }.execute(null, null, null); } private void storeRegistrationId(Context context, String regId) { int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app viewsion " + appVersion); settings.edit(); editor.putString(REG_ID, regId); editor.putInt(APP_VERSION, appVersion); editor.commit(); } 

    1. Certifique-se de que a class GCMRegister () tenha o método googleCloud.register no mesmo package (AndroidManifest.xml)

    2. Instale o aplicativo no celulair.

    Projeto 3.Clean and Run.

    4.That's Works !!

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.