Вопрос

Hi am getting duplicate notification from gcm server , how to resolve it

public class RegisterActivity{

    private GoogleCloudMessaging gcm;
    Context context;
    String regId;
    private static final String REG_ID = "regId";
    private static final String APP_VERSION = "appVersion";
    static final String TAG = "Register Activity";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private GCMRegistrationCallBack registeredActivity;
    private Error error;


    public void registerGCM(Context _context)
    {
        context = _context;
        if(!checkPlayServices()){
            Log.e(TAG, "This device is not supported.");
            return;
        }
        registeredActivity = (GCMRegistrationCallBack) _context;
        gcm = GoogleCloudMessaging.getInstance(context);
        regId = getRegistrationId(context);

        if(TextUtils.isEmpty(regId))
        {
             registerInBackground();

              Log.d("RegisterActivity",
                  "registerGCM - successfully registered with GCM server - regId: "
                      + regId);
        }
        else 
        {
            registeredActivity.didFinishRegisteringWithGCM(regId);
        }
    }

    private String  getRegistrationId(Context context) 
    {
        final SharedPreferences prefs = context.getSharedPreferences(
                GCMRegistrationCallBack.class.getSimpleName(), Context.MODE_PRIVATE);
        String registrationId = prefs.getString(REG_ID, "");
        if (registrationId.isEmpty()) {
              Log.i(TAG, "Registration not found.");
              return "";
            }
         int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
            int currentVersion = getAppVersion(context);
            if (registeredVersion != currentVersion) {
              Log.i(TAG, "App version changed.");
              return "";
            }
            return registrationId;
    }

    private static int getAppVersion(Context context) {
        try {
          PackageInfo packageInfo = context.getPackageManager()
              .getPackageInfo(context.getPackageName(), 0);
          return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
          Log.d("RegisterActivity",
              "I never expected this! Going down, going down!" + e);
          throw new RuntimeException(e);
        }
      }

    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
          @Override
          protected String doInBackground(Void... params) {
            try {
              if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
              }
              regId = gcm.register(Config.GOOGLE_PROJECT_ID);
              storeRegistrationId(context, regId);
            }
            catch(UnknownHostException _exception)
            {
                error = new Error("UnknownHostException");
                callErrorCallBackOnMainThread();

            }
            catch(SocketTimeoutException _exception)
            {
                error = new Error("SocketTimeoutException");
                callErrorCallBackOnMainThread();

            }
            catch (IOException _exception) {

                error = new Error(_exception.getMessage());
                callErrorCallBackOnMainThread();

            }
            catch(Exception _exception)
            {
                error = new Error("unknown exception");
                callErrorCallBackOnMainThread();

            }
            return regId;
          }

          @Override
          protected void onPostExecute(String msg) {
              if(!TextUtils.isEmpty(msg))
                  registeredActivity.didFinishRegisteringWithGCM(regId);
          }
        }.execute(null, null, null);
      }

    private void callErrorCallBackOnMainThread()
    {
        Activity regAvtivity = (Activity)registeredActivity;

        regAvtivity.runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                registeredActivity.didFailedToReceiveRegistrationId(error);
            }
        });
    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = context.getSharedPreferences(
                GCMRegistrationCallBack.class.getSimpleName(), Context.MODE_PRIVATE);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(REG_ID, regId);
        editor.putInt(APP_VERSION, appVersion);
        editor.commit();
      }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode,  (Activity)context,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");

            }
            return false;
        }
        return true;
    }

}

Above code for getting registration number please correct me anything wrong... but some time am getting duplicate notification. thanks

Это было полезно?

Решение

You should use Canonical IDs for this. This might happen because you registered with several IDs for the same device. Using canonical IDs will set your ID to be the last registration you've made.

As per the GCM reference about this:

Canonical IDs

On the server side, as long as the application is behaving well, everything should work normally. However, if a bug in the application triggers multiple registrations for the same device, it can be hard to reconcile state and you might end up with duplicate messages.

GCM provides a facility called "canonical registration IDs" to easily recover from these situations. A canonical registration ID is defined to be the ID of the last registration requested by your application. This is the ID that the server should use when sending messages to the device.

If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the registration_id field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working.

More info here.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top