【问题标题】:Foreground service start once and display activity on click前台服务启动一次并在点击时显示活动
【发布时间】:2020-06-24 17:52:58
【问题描述】:

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

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

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

【问题讨论】:

    标签: android android-service android-notifications


    【解决方案1】:

    #1。在启动服务之前,只需检查它是否已经运行。在这种情况下,这将对您有所帮助https://stackoverflow.com/a/5921190/6413387

    #2。要重新打开您上次打开的活动,您需要更新通知的待处理意图。希望你能在这里找到答案https://stackoverflow.com/a/20142620/6413387

    【讨论】:

      【解决方案2】:

      如何只创建一次前台通知,或者至少如何不在连续的 startForegroundService() 调用中播放通知声音?

      您可以检查通知是否已经可见并仅在不可见时显示。您需要有对通知 PendingIntent 和 notificationId 的引用。

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

      当我点击前台通知时如何返回我的应用程序?

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

      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,如果它已经与显示的最后一个活动可见。在这种情况下,您不必在 Preferences 上存储任何值,也不需要路由活动。

      【讨论】:

        猜你喜欢
        • 2021-09-15
        • 1970-01-01
        • 2020-03-17
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多