【问题标题】:Android onNewIntent always receives same IntentAndroid onNewIntent 总是收到相同的 Intent
【发布时间】:2012-12-12 11:04:31
【问题描述】:

我有 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); 
}

并在onNewIntent 方法中捕获Intent

@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(即,如果我单击IN 或OUT notification,则额外的意图始终包含相同的bundle(日志: OUT: false))。始终是最后创建的 Intent,我发现这是因为两个 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

【问题讨论】:

    标签: android android-intent android-notifications


    【解决方案1】:

    您为所有意图传递相同的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);
    

    【讨论】:

    • 如何定义我的请求代码?或者我应该制作 2 个请求代码,每个通知一个?或者他们应该等于他们的notification id?我现在在你说的那一行中有这段代码:incoming ? 678452056 : 678452099,这似乎有效,顺便说一句。
    • Intent.FLAG_ACTIVITY_NEW_TASK 不属于这里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2012-10-19
    相关资源
    最近更新 更多