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