使用PendingIntent的putExtra无法工作

22

我在我的 GCMIntentservice 中编写了一段代码,用于向多个用户发送推送通知。我使用 NotificationManager,在通知被点击时将调用 DescriptionActivity 类。我还将事件 ID 从 GCMIntentService 发送到 DescriptionActivity。

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

}

在上面的方法中,我获取的事件ID是正确的,即我始终获得更新后的事件ID。但在下面的代码(DescriptionActivity.java)中:

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

这里的event_id始终为"5"。无论我在GCMIntentService类中putExtra什么,我得到的event_id始终是5。有人能指出问题吗?是因为待处理意图吗?如果是,那我该如何处理?

3个回答

43

PendingIntent被重复使用并与您提供的第一个Intent一起使用,这是您的问题。

为避免此问题,请在调用PendingIntent.getActivity()以实际获取新的PendingIntent时,使用标志PendingIntent.FLAG_CANCEL_CURRENT

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

或者,如果你只想更新额外的内容,可以使用标志 PendingIntent.FLAG_UPDATE_CURRENT


太棒了!谢谢。 - Martin Pfeffer
PendingIntent pi = PendingIntent.getActivity(this,0, intent, PendingIntent.FLAG_CANCEL_CURRENT);意思是创建一个PendingIntent对象pi。这个对象可以用于发出启动活动的intent,同时FLAG_CANCEL_CURRENT表示如果现在有任何先前等待处理的相同PendingIntent,则取消它们。 - Alecs

12

正如Joffrey所说,PendingIntent将与您提供的第一个Intent重复使用。您可以尝试使用PendingIntent.FLAG_UPDATE_CURRENT标志。

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

5

也许您仍在使用旧的意图。尝试使用以下内容:

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

    handleIntentExtraFromNotification(intent);
}

非常感谢。我一直在与这个作斗争。 - Ifelere Bolaji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接