前台服务启动一次并在点击时显示 activity

Foreground service start once and display activity on click

我的应用程序中有 5 个活动。每个 activity 启动相同的前台服务。

在服务前台通知的 onStartCommand 方法中创建了不幸的是这意味着在任何 activity 中每次调用 startForegroundService() 都会播放通知声音(即使服务已经 运行)。如何仅创建一次前台通知或至少如何不在连续的 startForegroundService() 调用中播放通知声音?

另一个相关的问题是:点击前台通知后如何返回我的应用程序?我有 5 个活动,我想重新打开用户与之交互的最后一个 activity。

#1。在启动服务之前,只需检查它是否已经 运行。在这种情况下,这将帮助您

#2。要重新打开您上次打开的 activity,您需要更新通知的待处理意图。希望你能在这里找到你的答案

How can I create the foreground notification only once or at least how not to play notification sound on successive startForegroundService() calls?

您可以检查通知是否已经可见,只有在不可见时才显示。您需要参考通知 PendingIntent 和 notificationId。

fun isNotificationVisible(context: Context, notificationIntent: Intent, notificationId: Int): Boolean {
    return PendingIntent.getActivity(context, notificationId, notificationIntent, PendingIntent.FLAG_NO_CREATE) != null
}

how can I go back to my application when I click the foreground notification?

您需要 PendingIntent 才能从通知中打开应用程序。要打开显示的最后一个 activity,您可以使用每个 activity 的 onResume() 方法中的 Preferences 记住这一点,并将通知路由到一个路由 activity 中,该路由 activity 开始右边的 activity根据保存到首选项中的值。

val intent = Intent(context, RouteActivity::class.java)
val notificationBuilder = NotificationCompat.Builder(context, channelId)
    .setContentIntent(intent)
val notificationManager = NotificationManagerCompat.from(context)
val notification = notificationBuilder.build()
notificationManager.notify(notificationId, notification)

执行此操作的另一种方法是更新通知 PendingIntent(如果它在最后显示的 activity 中已经可见)。在这种情况下,您不必在 Preferences 上存储任何值,也不需要路由 activity.