android - 如何停止 Android Oreo 上的通知服务

标签 android service kotlin android-intentservice android-8.0-oreo

我们的应用程序有一些服务和 Intent 服务,它们会在用户启动应用程序时开始运行。即使用户最小化应用程序,也需要启动这些组件以继续运行进程。

在 Android Oreo 上,由于缺少使用 startForegroundService(:intent)startForeground(:id, :notification) 初始化这些服务,我们的应用开始崩溃。我们已根据要求修复它附加这些通知,但我们发现了一个奇怪的行为。即使应用程序在前台,这些通知也会出现,因为它没有意义,因为我们的服务几乎所有时间都在短时间运行,但需要保证 100% 的时间运行。这就是流程在服务上而不是在 Activity 的上下文中运行的原因。我只想在用户最小化应用程序并且服务启动时显示这些通知。 有什么办法吗?

enter image description here

我无法更改此消息,非常烦人!

下面是一些用于创建 channel 的代码:

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)

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

谢谢!

编辑 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();

关于android - 如何停止 Android Oreo 上的通知服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036945/

相关文章:

android - 动态壁纸启动问题

android - 我可以在没有 'page=number' 查询的情况下将 Paging3 库用于 API 吗?

java - 如何从 BindingAdapter 访问数据绑定(bind)变量

android - 如何在 Jetpack Compose 中处理 Mapbox map 的 Activity 生命周期事件?

android - 根据选择器中选择的应用程序,将不同的文本设置为 ACTION_SEND Intent

android - 无法将已编译的着色器链接到 OpenGL ES 2.0 Android 程序

android - 在 Android Studio 中导入 Urban Airship 会出现编译问题?

bash - bash 中的 while 循环使用 pgrep 检查服务是否存在

java - 如何启动/停止/重新启动 Linux 服务以及如何从 Java 程序更新它们的配置文件

c++ - 以编程方式重新启动所有崩溃服务的服务程序