Android PendingEvent.FLAG_UPDATE_当前重新创建活动

Android PendingEvent.FLAG_UPDATE_当前重新创建活动,android,android-intent,push-notification,android-notifications,android-pendingintent,Android,Android Intent,Push Notification,Android Notifications,Android Pendingintent,我有一个通知,当我点击它时,如果应用程序仍然没有运行,我想启动它,但如果应用程序已经运行,我不想重新启动它。 因此,在创建pendingent时,我使用了pendingent.FLAG\u UPDATE\u CURRENT标志 我的代码: private val notificationManager by lazy { NotificationManagerCompat.from(this) } fun testPush() { val notificationBuilder

我有一个通知,当我点击它时,如果应用程序仍然没有运行,我想启动它,但如果应用程序已经运行,我不想重新启动它。 因此,在创建
pendingent
时,我使用了
pendingent.FLAG\u UPDATE\u CURRENT
标志

我的代码:

private val notificationManager by lazy { NotificationManagerCompat.from(this) }

fun testPush() {
        val notificationBuilder = NotificationCompat.Builder(this, BuildConfig.APPLICATION_ID)
                .setSmallIcon(R.drawable.ill_launcher)

        notificationBuilder
                .setContentTitle("Title")
                .setContentText("Test text")
                .setContentIntent(buildPendingIntent())

        notificationBuilder
                .setAutoCancel(true)
                .priority = NotificationCompat.PRIORITY_DEFAULT

        notificationManager.notify(1, notificationBuilder.build())
}

 private fun buildPendingIntent(): PendingIntent {

        val intent = Intent(this, RootActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        intent.putExtra("action", RootActivity.DEFAULT_INTENT)

        return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

但是,当我启动应用程序并单击通知时,活动将重新创建。

您需要为您的应用程序创建一个“启动
意图”
,而不是像现在这样为
RootActivity
构建
意图。最简单的方法是调用
PackageManager.getLaunchIntentForPackage()
并传递您自己的包名。在调用
pendingent.getActivity()
时使用返回的
Intent


如果应用程序未运行,这将启动应用程序;否则,如果应用程序已运行,则只会将包含应用程序的现有任务带到前台。

FLAG\u UPDATE\u CURRENT
没有此效果。这意味着您要更新
Intent
的附加内容,如果已经有一个
pendingent
对应的
Intent
。它没有说明是否要重用现有的活动实例。@commonware因此,我需要为
Intent
设置一些标志以获得所描述的效果,对吗?此处:
intent.flags=intent.
。文档中说,
Intent.FLAG\u ACTIVITY\u SINGLE\u TOP
将以描述的方式工作:“如果活动已经在历史堆栈的顶部运行,则不会启动它”。但是我的应用程序不是这样工作的。默认情况下,您将得到一个新任务,因为
pendingent
正在从任务的现有活动中调用。IIRC,您需要在清单中的
元素中调整一些与任务相关的属性。@commonware您能提供示例吗?你是说smth喜欢android:launchMode属性吗?我手头没有这个示例,抱歉。它仍然会重新创建活动,这让人难以置信。请编辑您的问题并发布您的清单,以及用于创建
pendingent
的代码。另外,您如何知道
活动
已重新创建?请尝试Android 6、7