Android GCM not working after Lollipop update on d

2019-06-08 01:05发布

问题:

I implemented GCM for push notifications like stated in the Android Guide (https://developer.android.com/google/gcm/client.html) in one of my apps. The app and notifications are working fine on Kitkat and Lollipop.

But lastly I became some mails from users that upgraded their phones from to Lollipop. With that the notifications will not be displayed anymore. Only solution so far is to remove the app and reinstall it from the appstore.

Did someone face a similar problem and if so, did you find a solution to fix it?

回答1:

This is a GCM ID issue. Try using Thread.sleep and retry for a number of times, till the GCM ID is recieved.

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 ++;
       GCMRegistrar.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 = GCMRegistrar.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 shared preferences
            saveRegIDToSharedPreferences(); 
        }


   }

The Thread.sleep and noOfAttemptsAllowed can be played around with based on your design and other parameters. We had a sleep time of 7000 so that probability of getting registered at first attempt is higher. However, if it fails, the next attempt would consume another 7000ms. This might cause users to think your app is slow. So, play around intelligently with those two values.