【发布时间】:2019-09-21 02:40:43
【问题描述】:
我有一个通知,当我点击它时,如果它仍未运行,我想启动应用程序,但如果应用程序已经运行,我不想重新启动它。
所以,我在创建PendingIntent 时使用了PendingIntent.FLAG_UPDATE_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)
}
但是当我启动应用程序并单击通知时,会重新创建活动。
【问题讨论】:
-
FLAG_UPDATE_CURRENT没有这种效果。这表示您想要更新Intent的附加功能,如果已经有一个PendingIntent对应的Intent。它没有说明您是否要重用现有的活动实例。 -
@CommonsWare 所以,我需要为
Intent设置一些标志来获得描述的效果,对吧?在这里:intent.flags = Intent.<SOME_FLAG>。文档说,Intent.FLAG_ACTIVITY_SINGLE_TOP将以所描述的方式工作:“如果活动已经在历史堆栈的顶部运行,则不会启动它”。但是我的应用程序不是这样工作的。 -
默认情况下,您将完成一个新任务,因为
PendingIntent是从您的任务现有活动之一以外的其他活动中调用的。 IIRC,您需要在清单中的<activity>元素中调整一些与任务相关的属性。 -
@CommonsWare 你能提供例子吗?你是说
android:launchMode属性之类的东西吗? -
我没有这个方便的样品,抱歉。
标签: android android-intent push-notification android-notifications android-pendingintent