GCM to implement push notification on Android

2019-08-07 22:41发布

问题:

Below is my code of client:

public class GCMIntentService extends GCMBaseIntentService {
    public GCMIntentService() {
        super(SENDER_ID);
    }
    @Override
    protected void onError(Context arg0, String arg1) {
    }
    @Override
    protected void onMessage(Context arg0, Intent arg1) {
        Context context = getApplicationContext();
        String NotificationContent = arg1.getStringExtra("message");
        System.out.println("Message: " + NotificationContent);
    }
    @Override
    protected void onRegistered(Context arg0, String arg1) {
        System.out.println("Registered id: " + arg1);
    }
    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        System.out.println("Unregistered id: " + arg1);
    }
}

And Registering and Unregistering method as below:

public void Registering() {
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    RegistrationId = GCMRegistrar.getRegistrationId(this);
    if(RegistrationId.equals("")) {
        GCMRegistrar.register(this, SENDER_ID);
    }
}
public void Unregistering() {
    Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
    unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    startService(unregIntent);
}

On the same device, the first time call Registering(), I got registered_id_1.
And I call Unregistering(), it will print: Unregistered id: registered_id_1 means unregistering success.
And call Registering() again, it will get another registered_id_2.

And the push notification server I send message to registered_id_1 as below code:

Sender sender = new Sender("Android API Key");// Android API KEY
Message message = new Message.Builder().addData("message", My Message).build();
Result result = null;
try {
    result = sender.send(message, registered_id_1, 5);
} catch (IOException e) {
    e.printStackTrace();
}

But the client still receives the message that send to registered_id_1.
What is wrong in my method?

回答1:

There is nothing wrong in your method. That's the behavior of GCM. When a device gets a new registration ID for a given app, the old registration IDs previously assigned for this device and app will still work. If you send a GCM message using the old registration ID, you'll get a response containing a canonical registration ID (whose value is the new registration ID for that device). When you get such a response, you should eliminate the old registration ID from your server's DB.

Or you can handle it better if when un-registering the old registration ID you'll also notify your server, which will remove the old registration ID and never try to send a message to it again.