android - 从通知启动时防止重新创建 Activity Activity

标签 android android-intent android-activity android-notifications android-pendingintent

从 Android Oreo 8.0 (26 API) 开始,当使用代码启动 Activity 时,如果先前的实例没有被销毁并且仍然存在,它不会创建新的 Activity,但在以前的 Android(例如 Marshmallow、Nougat)上,它总是创建无论如何都是一个新 Activity 。

为什么它的行为因 Android 版本而异?

我想阻止创建新的 Activity 实例,并在单击通知时从 Android 23 (Marshmallow) 开始将现有的 Activity 实例置于前面(如果它仍然存在)。目前它只能从 Oreo Android (26) 开始工作

val intent = Intent(this, TestActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

val pendingIntentt = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
)

val ... = NotificationCompat.Builder(this, channelId)
    ...
    .setContentIntent(pendingIntent)

最佳答案

如果您想将应用程序的现有实例带到前台,或者在应用程序未运行(前台或后台)时创建一个新实例,则只需在您的通知:

val intent = getPackageManager.getLaunchIntentForPackage("my.package.name")

关于android - 从通知启动时防止重新创建 Activity Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63873057/

相关文章:

android - 在 android : activity vs fragment 中使用底部导航的最佳实践

android - 仅创建一个Media Player实例

java - 当我从另一 Activity 获取结果时,ListView 仅更新一个 View 项,如何获取所有过去的结果?

android - 移动安卓设备的CSS : white border above background-image doesn't want to dissapear

java - 使用传递的字符串调用资源

java - 如何使用 Android 代码中的 GCM CCS 进行上游消息服务?

java - 将额外数据从 Activity 传递到 Intent

android - 没有可重用的 UI 使用什么 Activity 或 Fragment?

android - 未调用 Firebase onDataChange

java - 改造中url的动态变化