Android onNewIntent始终接收相同的Intent

时间:2012-12-12 11:04:32

标签: android android-intent android-notifications

我有2 Notifications:一个用于传入消息,一个用于传出消息。在Notification点击后,它会将PendingIntent发送给自己。我输入了一个额外的值来确定点击了Notifications中的哪一个:

private static final int INID = 2;
private static final int OUTID = 1;

private void update(boolean incoming, String title, String message, int number) {
    notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = new Intent(this, Entry.class);
    intent.putExtra((incoming ? "IN" : "OUT"), incoming);
    PendingIntent pi = PendingIntent.getActivity(Entry.this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification noti = new Notification(incoming ? R.drawable.next : R.drawable.prev, incoming ? "Incoming message" : "Outgoing message", System.currentTimeMillis());
    noti.flags |= Notification.FLAG_NO_CLEAR;
    noti.setLatestEventInfo(this, title, message, pi);
    noti.number = number;
    notificationManager.notify(incoming ? INID : OUTID, noti); 
}

并捕获Intent方法中的onNewIntent

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    if (intent.getExtras() != null) 
        for (String id : new ArrayList<String>(intent.getExtras().keySet())) {
            Object v = intent.getExtras().get(id);
            System.out.println(id + ": " + v);
        }
    else
        log("onNewIntent has no EXTRAS");
}

加上manifest行,确保只有一个任务(在activity标记中):

android:launchMode="singleTop" 

我记录它通过onNewIntent方法运行,但总是使用相同的intent(IE如果我点击IN或OUT notification,则额外的intent总是包含相同的bundle(日志:OUT: false))。它始终是最后创建的Intent,我发现它是因为两个意图的初始化发生在另一个序列中而不是它们被更改时:

private void buttonClick(View v) {      
    update(true, "IN", "in", 1);
    update(false, "OUT", "out", 3);
}

private void setNotificationSettings() {
    update(false, "IN", "===out message===", 0);
    update(true, "OUT", "===in message===", 0);
}

为什么我总是收到相同的(上次创建的)Intent

1 个答案:

答案 0 :(得分:7)

您正在传递相同的requestcode以表示您每次都记得最后一次意图的所有意图,因此您必须在未决意图中传递不同的requestcode

如下面的代码

您的代码:

 PendingIntent pi = PendingIntent.getActivity(Entry.this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

需要更改:

PendingIntent pi = PendingIntent.getActivity(Entry.this, your_request_code, intent, Intent.FLAG_ACTIVITY_NEW_TASK);