【发布时间】:2020-05-29 09:10:30
【问题描述】:
我有一个使用 IntentService 在后台工作的应用程序,即使它已关闭。
有一个按钮可以启动后台进程并出现通知。在用户按下另一个停止 IntentService 的按钮之前,此通知不会消失。
但这里我遇到了另一个问题。我第一次启动一个应用程序。然后按下初始化 IntentService 的按钮,出现通知。在那之后,当应用程序仍在屏幕上时,我按下通知,看起来应用程序创建了它的副本。我可以多次单击通知,并创建了许多应用程序副本。
刚刚发现了一些技巧,例如向 PendingIntent 添加标志并在清单中插入一些字符串,但到目前为止没有任何帮助。
也许我需要更改通知或待处理意图?
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createNotificationChannel()
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT
)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service Kotlin Example")
.setContentText("kylsha")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
return super.onStartCommand(intent, flags, startId)
}
这是它的样子
我希望仅在应用程序关闭或最小化时通知启动活动,而不是创建它的多个副本。是不是应该对pendingIntent做点什么?
【问题讨论】:
-
你试过了吗? developer.android.com/training/notify-user/navigation。您必须对活动的未决意图使用 UPDATE_CURRENT flat。您将在活动中使用更新的意图获得回调 onNewIntent 方法。我曾经遇到过类似的问题,我特别记得使用 onNewIntent 回调来获取带有 UPDATE_CURRENT 标志的新意图以用于挂起的意图。
-
@JudeOsbertK 谢谢,你是对的。除此之外,我还必须在 Manifes 的 acritivity sectiont 中添加一些字符串:
android:launchMode="singleTask" android:taskAffinity="" android:excludeFromRecents="true"
标签: android kotlin android-intent android-activity notifications