gpt4 book ai didi

需要 Android 通知 : Intent. FLAG_ACTIVITY_NEW_TASK?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:59:53 24 4
gpt4 key购买 nike

Notification 类的文档中,我看到了这个:

public PendingIntent contentIntent

The intent to execute when the expanded status entry is clicked. If this is an activity, it must include the FLAG_ACTIVITY_NEW_TASK flag, which requires that you take care of task management as described in the Tasks and Back Stack document. In particular, make sure to read the notification section Handling Notifications for the correct ways to launch an application from a notification.

我已经阅读了上面链接的 Material ,但我还是不明白。为什么要通过单击通知启动 Activity 时需要 FLAG_ACTIVITY_NEW_TASK 标志?我尝试了以下代码:

NotificationManager manager = (NotificationManager)context.
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
android.R.drawable.stat_notify_sync, title,
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(context, NotifiedActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // IS THIS REALLY REQUIRED??
PendingIntent pt = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, title, text, pt);
manager.notify(0, notification);

我运行了上面的代码,有和没有 intent.setFlags 行,似乎没有区别。事实上,我发现的许多代码示例根本就没有那一行。那么为什么文档说 FLAG_ACTIVITY_NEW_TASK 标志是必须的,它在通知处理方面究竟有什么区别?

最佳答案

从技术上讲,这个标志是必需的。但由于它是必需的,Android 很好,会为您设置它;-)

需要它的原因如下:

处理 Notification 并调用 startActivity() 以实际启动 Intent 的代码未在“任务”中运行.它是系统代码,是 Notification 系统的一部分。通常,如果您调用 startActivity() 并且 Intent.FLAG_ACTIVITY_NEW_TASK 标志未设置,Android 将尝试将该 Activity 启动到当前任务中(即:包含正在调用 startActivity() 的 Activity 的任务)。因为在这种情况下,没有任务,Android 必须将 Activity 启动到另一个任务中。这就是您需要指定 Intent.FLAG_ACTIVITY_NEW_TASK 的原因。

在实践中,这不会总是创建一个新任务,因为 Android 会首先尝试找到一个(合适的)现有任务来启动 Activity。如果您的应用程序已经在运行,Android 只会将 Activity 启动到该任务中。 (这不是 100% 正确,还有其他特殊情况可以改变这个逻辑,但我不打算在这里解决它们)。

注意:如果您从 ServiceBroadcastReceiver 调用 startActivity(),也会出现同样的情况。在这些情况下,标志 Intent.FLAG_ACTIVITY_NEW_TASK 必须设置,因为没有“当前任务”,所以 Android 必须将 Activity 启动到另一个任务。

关于需要 Android 通知 : Intent. FLAG_ACTIVITY_NEW_TASK?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30886618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com