[英]GCM to implement push notification on Android
以下是我的客戶代碼:
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
的消息。
我的方法有什么問題?
您的方法沒有錯。 這就是GCM的行為。 當設備獲得給定應用程序的新注冊ID時,先前為此設備和應用程序分配的舊注冊ID仍將起作用。 如果您使用舊的注冊ID發送GCM消息,則會收到包含規范注冊ID(其值為該設備的新注冊ID)的響應。 收到此類響應時,應從服務器的數據庫中刪除舊的注冊ID。
或者,如果注銷舊的注冊ID時還通知服務器,則服務器會更好地處理該問題,服務器將刪除舊的注冊ID,並且從不嘗試再次向其發送消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.