点击通知时启动 IntentService 会导致应用程序崩溃

Launching IntentService when tapping notification causes app to crash

当用户点击 android Oreo 及更高版本上的通知时,应用程序崩溃:java.lang.IllegalStateException:不允许启动服务 Intent。我了解这是因为 android Oreo 中引入的后台服务限制。但是我不确定我有什么选择,因为我需要在用户点击通知后立即启动一个 IntentService 来做一些简短的后台工作。

在 FCM 的 onMessageReceived 方法中:

    val denyIntent = Intent(this, DenyService::class.java)
    denyIntent.putExtra(VIDEO_EXTRA_SESSION_ID, sessionId)
    denyIntent.putExtra(VIDEO_DENY_REASON, "callee_action_deny")
    val denyIntentCode = System.currentTimeMillis().toInt()
    val pendingIntentDeny = PendingIntent.getService(this, denyIntentCode, denyIntent, 0)
    notificationBuilder.setDeleteIntent(pendingIntentDeny)
    notificationBuilder.addAction(
            R.drawable.ic_call_reject,
            getString(R.string.chat_action_reject),
            pendingIntentDeny
    )



class DenyService : IntentService("DenyCall")

对于启动 ServiceIntentService 的限制没有区别。当您的应用程序不在前台时,该限制适用于在后台启动服务,因此适用于两者。

由于您正在处理 Notification 并且无法控制服务的启动,您可以执行以下操作:

方法一

对于API级别Android O及以上,而不是PendingIntent.getService,使用PendingIntent.getForegroundService

this will start a foreground service, like calling Context.startForegroundService()

将您的 IntentService 转换为服务,并立即通过显示通知并调用 startForeground() 使其成为前台服务。

接近 2:

基于documentation:

Under following circumstances, a background app is placed on a temporary whitelist for several minutes:

  • Handling a high-priority Firebase Cloud Messaging (FCM) message.
  • Receiving a broadcast, such as an SMS/MMS message.
  • Executing a PendingIntent from a notification.

当应用程序在白名单中时,它可以不受限制地启动服务,并且允许其后台服务运行。

你的情况很奇怪,你不能 运行 IntentService,可能是因为没有可见的通知。您可以扩展 Service 并立即通过显示通知并调用 startForeground().

使其成为前台服务

方法三:

使用 JobIntentService。按照此 了解实施细节