android - 来自通知的 Intent 没有额外内容

标签 android android-intent android-notifications

这似乎是一个常见问题,我已经找到了所有相关问题: Activity isn't picking up new intentWhy extra data (integer) is not sent in android notification intent?Notification passes old Intent ExtrasCan't put extras for an intent in notificationandroid pending intent notification problem;但仍然无法弄清楚。

问题是一样的。我设置了一个带有 PendingIntent 的通知,其中包含一些额外的信息,但我没有在另一边得到它。

这是生成通知的代码:

Notification notification = new Notification(R.drawable.icon, getResources().getString(R.string.notification_ticker), System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;

Intent start_test = new Intent(this, MyActivity.class);
start_test.putExtra("start_test", true);
start_test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

PendingIntent pi = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), start_test, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, getResources().getString(R.string.notification_title), getResources().getString(R.string.notification_content, expired), pi);
nm.notify(NOTIFICATION_ID, notification);

另一方面:

boolean start_test=getIntent().getBooleanExtra("start_test", false);

bundle 实际上不存在(getExtras() 返回 null)。

我尝试了 PendingIntent.getActivity 的不同标志(FLAG_UPDATE_CURRENTFLAG_CANCEL_CURRENTFLAG_ONE_SHOT),没有一个那些有帮助的。

如代码所示,我使用 getCurrentMillis 来确保 requestID 发生变化......

还发现在 MyActivity 中,onCreateonNewIntent 没有被调用。只有 onResume 是。即使设置了 FLAG_ACTIVITY_NEW_TASK...?

我错过了一些非常简单的东西吗?

最佳答案

为通知 Intent 设置 FLAG_ACTIVITY_NEW_TASK 会导致以下情况:

  • 如果 Activity 已经在任务中运行,则将启动一个新任务,并将 Intent 传递给 onCreate() 中的 Activity

  • 但是,如果 Activity 已经在任务中运行,则该任务将被带到前台。就这样。 Intent 将被传递,并且 onNewIntent() 将不会被调用。

如果您希望 Intent 实际交付,您需要指定:

start_test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);

没有区别activity的launchMode是否为singleTop,还是要指定Intent.FLAG_ACTIVITY_SINGLE_TOP 在 Intent 中。

注意:如果 Activity 已经在某个任务中运行,并且该 Activity位于该任务中的 Activity 堆栈顶部,则该任务将被带到前景。就这样。 Intent 将不会交付。实现这一点的唯一方法是将 Intent.FLAG_ACTIVITY_CLEAR_TOP 添加到其他 2 个标志,但这可能不是您想要发生的(取决于您的具体情况)。

http://code.google.com/p/android/issues/detail?id=17137 上查看我在 Google 代码上的(仍然)未决问题

关于android - 来自通知的 Intent 没有额外内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11551195/

相关文章:

Android 11 (R) 在查询 ACTION_IMAGE_CAPTURE 的 Intent 时返回空列表

Android:从通知启动外部应用程序

android - 重启后丢失通知访问权限

java - 如何从您的 Activity 的前一个实例中判断线程已经完成?

android - 如何在TextView中创建垂直对齐的上标和下标

android - Google Cloud Messaging (GCM) - 无法实例化接收器 - java.lang.ClassNotFoundException

java - intent.resolveActivity(getPackageManager()) 究竟在做什么?

java - 根据按钮链接在 webview 中显示特定的 url

java - Android Intent 选择设置默认应用

android - Android Marshmallow 上的白色通知图标