簡體   English   中英

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

[英]How to stop notification's service on Android Oreo

我們的應用程序有一些服務和意圖服務,它們會在用戶啟動應用程序時開始運行。 即使用戶最小化應用程序,也需要啟動這些組件以繼續運行進程。

在 Android Oreo 上,由於缺少使用startForegroundService(:intent)startForeground(:id, :notification)初始化這些服務,我們的應用程序開始崩潰。 我們已修復它附加這些通知作為請求,但我們發現了一個奇怪的行為。 即使應用程序在前台,這些通知也會出現,因為它沒有意義,因為我們的服務幾乎一直都在短時間運行,但需要保證 100% 的時間運行。 這就是流程在服務上運行而不是在活動的上下文中運行的原因。 我想僅在用戶最小化應用程序並且服務啟動時才顯示這些通知。 有什么辦法嗎?

在此處輸入圖片說明

我無法更改此消息,非常煩人!

以下是用於創建頻道的一些代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM