21

我在我的GCMIntentservice中編寫了一個代碼,它將推送通知發送給許多用戶。我使用NotificationManager,當通知被點擊時它將調用DescriptionActivity類。我還派事項標識形成GCMIntentService到DescriptionActivityputExtra使用掛起的意圖不起作用

protected void onMessage(Context ctx, Intent intent) { 
    message = intent.getStringExtra("message"); 
    String tempmsg=message; 
    if(message.contains("You")) 
    { 
     String temparray[]=tempmsg.split("="); 
     event_id=temparray[1]; 
    } 
    nm= (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    intent = new Intent(this, DescriptionActivity.class); 
    Log.i("the event id in the service is",event_id+""); 
    intent.putExtra("event_id", event_id); 
    intent.putExtra("gcmevent",true); 
    PendingIntent pi = PendingIntent.getActivity(this,0, intent, 0); 
    String title="Event Notifier"; 
    Notification n = new Notification(R.drawable.defaultimage,message,System.currentTimeMillis()); 
    n.setLatestEventInfo(this, title, message, pi); 
    n.defaults= Notification.DEFAULT_ALL; 
    nm.notify(uniqueID,n); 
    sendGCMIntent(ctx, message); 

} 

這裏說我得到上述方法的事項標識是正確的即我總是得到更新之一。但是在下面的代碼中(DescriptionActivity.java):

intent = getIntent(); 
    final Bundle b = intent.getExtras(); 
    event_id = Integer.parseInt(b.getString("event_id")); 

event_id這裏始終是「5」。不管我在GCMIntentService類中放置了什麼,我得到的event_id總是5.有人可以指出這個問題嗎?是因爲未決的意圖?如果是的話,那我該如何處理呢?

回答

41

PendingIntent與您提供的第一個Intent重複使用,這是您的問題。

爲了避免這種情況,可以使用標誌PendingIntent.FLAG_CANCEL_CURRENT當你調用PendingIntent.getActivity()真正得到一個新的:

PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 

或者,如果你只是想更新的額外內容,使用標誌PendingIntent.FLAG_UPDATE_CURRENT

+0

謝謝很多人!它的工作:) – Nemin 2013-05-04 17:52:54

+0

真棒的答案!謝謝。 – 2015-12-27 08:24:19

+0

如果它不清楚:PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT); – Alecs 2016-01-29 12:10:59

12

的PendingIntent與您提供的第一個Intent重複使用,就像Joffrey所說的那樣。您可以嘗試使用PendingIntent.FLAG_UPDATE_CURRENT標誌。

PendingIntent pi = PendingIntent.getActivity(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
4

也許你仍在使用舊的意圖。試試這個:

@Override 
protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 
    //try using this intent 

    handleIntentExtraFromNotification(intent); 
} 
+0

非常感謝。我一直在與此作鬥爭 – 2016-11-02 15:14:08