如何在Android Oreo上停止通知服务

3
我们的应用程序有一些服务和意图服务,当用户启动应用程序时会开始运行。即使用户最小化应用程序,这些组件也需要启动以继续处理过程。在Android Oreo上,由于没有使用startForegroundService(:intent)startForeground(:id, :notification)初始化这些服务,我们的应用程序开始崩溃。我们已经修复了这个问题,并将这些通知作为必需附加,但我们发现一个奇怪的行为。即使应用程序在前台运行,这些通知也会出现,因为这并没有意义,因为我们的服务几乎总是短暂运行,但它需要保证100%运行时间。这就是为什么该进程在服务中而不是在活动的上下文中运行。我希望只有当用户最小化应用程序并且服务正在运行时才显示这些通知。有办法实现吗?

enter image description here

我可以翻译这条消息,非常烦人!以下是用于创建频道的一些代码:
const val SERVICE_CHANNEL_ID = "com.myFunnyApp.notifications"
//.....
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val notificationService = context.getSystemService(Context.NOTIFICATION_SERVICE)
  (notificationService as? NotificationManager)?.let { notificationManager ->

    if (notificationManager.getNotificationChannel(SERVICE_CHANNEL_ID) == null) {
      val channel = NotificationChannel(
          SERVICE_CHANNEL_ID,
          context.resources.getString(R.string.test),
          NotificationManager.IMPORTANCE_MIN)
      channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
      notificationManager.createNotificationChannel(channel)
      return
    }

  }

}

在服务上,代码运行:

val notification = Notification.Builder(context, SERVICE_CHANNEL_ID)
        .setSubText("subText") //Not working
        .setContentText("contentText") //Not working
        .setSettingsText("settingsText") //Not working
        .setContentTitle("title") //Not working
        .build()
startForeground(1, notification)

目前我正在模拟器上测试,没有任何安卓Oreo设备。

谢谢!

编辑1:只有在设置小图标时文本才会更改。


你在清单文件中定义了不同的“进程”吗?你的服务需要多长时间才能完成? - Arnav M.
1个回答

1
在Android 8.0(Android Oreo)及以上版本中,我们必须将服务带到前台,然后才能触发通知。 之后,一旦触发了通知,您将需要停止在前台运行的服务,为此,请执行以下代码 -
val notification = Notification.Builder(context, SERVICE_CHANNEL_ID)
        .setSubText("subText") //Not working
        .setContentText("contentText") //Not working
        .setSettingsText("settingsText") //Not working
        .setContentTitle("title") //Not working
        .build()
startForeground(1, notification)

stopForeground(true);
stopSelf();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接