【问题标题】:Launching IntentService when tapping notification causes app to crash点击通知时启动 IntentService 会导致应用程序崩溃
【发布时间】:2018-12-08 03:57:27
【问题描述】:

当用户在 Android Oreo 及更高版本上点击通知时应用程序崩溃:java.lang.IllegalStateException: Not allowed to start service 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")

【问题讨论】:

  • 创建前台服务
  • @Psypher 问题是该服务是使用 PendingIntent 启动的,客户端代码无法控制服务的启动方式。

标签: android android-notifications


【解决方案1】:

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

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

方法 1

对于 API 级别 Android O 及以上,请使用 PendingIntent.getService 代替 PendingIntent.getForegroundService

这将启动一个前台服务,例如调用 Context.startForegroundService()

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

方法 2:

基于documentation:

在以下情况下,后台应用程序被放置在 临时白名单几分钟:

  • 处理高优先级 Firebase 云消息传递 (FCM) 消息。
  • 接收广播,例如 SMS/MMS 消息。
  • 从通知中执行 PendingIntent。

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

奇怪的是,您无法运行IntentService,可能是因为没有可见的通知。您可以扩展 Service 并立即通过显示通知和调用 startForeground() 使其成为前台服务。

方法 3:

使用 JobIntentService。关注这个SO了解实现细节

【讨论】:

  • 服务由框架代码启动,因为它是一个通知PendingIntent。我们不能在应用代码中调用 Context.startForegroundService。
  • 一个IntentService也是一个Service,当它用于处理来自通知的PendingIntent时,它不应该在白名单中吗?
  • 我在特定设备(如三星设备)上遇到了同样的问题。当用户单击通知上的操作按钮(应该启动意图服务)时 - IntentService 未启动且 onHandleIntent 未执行。
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 2021-12-31
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多