如何以编程方式从通知中恢复 Activity?

How to programmatically resume an Activity from a notification?

我已经阅读了很多关于该主题的答案,但其中 none 解决了这个问题。

应用 运行 "foreground service" 因此需要通知。

这就是 Intent 的创建方式。

Intent intent = new Intent(context, notificationClass);
return PendingIntent.getActivity(context, 0, intent, 0);

请注意,从通知中启动的 Activity class 在运行时是已知的 (notificationClass)。对于额外的上下文,有一个公开 View 的库,它在膨胀时创建 Service,它创建 Notification,因为任何 Activity 都可以包含 View,请求 Class 以便在用户单击通知时恢复正确的 Activity.

然后,intent 被添加到 notificationBuilder (NotificationCompat.Builder)。

notificationBuilder.setContentIntent(intent);

当应用进入后台然后点击通知时执行此操作,它会创建 Activity 的新副本而不是恢复它。

出于测试目的,通过将 Activity(事先知道)的 launchMode 添加到 singleTopAndroidManifest.xml 文件中。但我无法以任何其他方式让它工作。

有了这些约束,我想知道在创建 Notification 时是否有可能以编程方式获得相同的行为。我已经尝试了一堆 Intent 标志组合(还有 addFlagssetFlags),但没有成功。

是否有可能创建一个 Intent 以按照解释的方式行事?

非常感谢!

抄送 https://whosebug.com/users/769265/david-wasser 已经回答了很多类似的 Intent 相关问题

不知道我是否完全理解,但如果你只是想将现有任务调到前台(这与从最近任务列表中选择一个任务相同),那么试试这个:

PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(packageName);
return PendingIntent.getActivity(context, 0, intent, 0);

packageNameAndroidManifest.xml中的包名。

这个 "launches" 任务的根 Activity,它实际上不会启动任何东西,只是将现有任务带到前台。

经过反复试验,我使用以下方法组合使其正常工作

PackageManager pm = context.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
intent.setPackage(null);
return PendingIntent.getActivity(context, 0, intent, 0);enter code here

这里的关键部分是 intent.setPackage(null);

/**
 * (Usually optional) Set an explicit application package name that limits
 * the components this Intent will resolve to.  If left to the default
 * value of null, all components in all applications will considered.
 * If non-null, the Intent can only match the components in the given
 * application package.
 *
 * @param packageName The name of the application package to handle the
 * intent, or null to allow any application package.
 *
 * @return Returns the same Intent object, for chaining multiple calls
 * into a single statement.
 *
 * @see #getPackage
 * @see #resolveActivity
 */

显然,pm.getLaunchIntentForPackage(context.getPackageName()); returns 一个 Intent 仅限于 context.getPackageName() 中的组件,并且之后需要将包明确设置为 null 以便所有组件都被考虑在内。

虽然我不是很确定^。 FWIW 添加它,解决了问题¯\_(ツ)_/¯