【问题标题】:GCM to implement push notification on AndroidGCM 在 Android 上实现推送通知
【发布时间】:2014-03-25 09:07:05
【问题描述】:

下面是我的客户端代码:

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);
    }
}

注册和注销方法如下:

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);
}

在同一台设备上,第一次拨打Registering(),我得到了registered_id_1
我打电话给Unregistering(),它会打印: Unregistered id: registered_id_1 表示注销成功。
并再次调用Registering(),它将得到另一个registered_id_2

以及我向registered_id_1 发送消息的推送通知服务器,代码如下:

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();
}

但是客户端仍然收到发送到registered_id_1的消息。
我的方法有什么问题?

【问题讨论】:

    标签: android push-notification google-cloud-messaging


    【解决方案1】:

    你的方法没有错。这就是 GCM 的行为。当设备为给定应用程序获取新的注册 ID 时,之前分配给该设备和应用程序的旧注册 ID 仍然有效。如果您使用旧注册 ID 发送 GCM 消息,您将收到包含规范注册 ID(其值是该设备的新注册 ID)的响应。当您收到这样的响应时,您应该从服务器的数据库中删除旧的注册 ID。

    或者,如果在取消注册旧的注册 ID 时您也会通知您的服务器,这将删除旧的注册 ID 并且不再尝试向其发送消息,那么您可以更好地处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2016-07-24
      • 2015-03-08
      • 1970-01-01
      相关资源
      最近更新 更多