Android 8.0:java.lang.IllegalStateException:不允许启动服务Intent

在应用程序启动时,应用程序启动应该执行某些网络任务的服务.
在针对API级别26后,我的应用程序无法在后台启动Android 8.0上的服务.

Caused by: java.lang.IllegalStateException: Not allowed to start
service Intent {
cmp=my.app.tt/com.my.service
}: app is in background uid UidRecord{90372b1 u0a136 CEM idle procs:1
seq(0,0,0)}

据我所知,它涉及到:
Background execution limits

The startService() method now throws an IllegalStateException if an
app targeting Android 8.0 tries to use that method in a situation when
it isn’t permitted to create background services.

“在不允许的情况下” – 它实际意味着什么?以及如何解决它.我不想把我的服务设置为“前景”

最佳答案
允许的情况是临时白名单,其中后台服务的行为与Android O之前相同.

Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that’s visible to the user, such as:

  • Handling a high-priority Firebase Cloud Messaging (FCM) message.
  • Receiving a broadcast, such as an SMS/MMS message.
  • Executing a PendingIntent from a notification.
  • Starting a VpnService before the VPN app promotes itself to the foreground.

资料来源:https://developer.android.com/about/versions/oreo/background.html

换句话说,如果您的后台服务不符合白名单要求,则必须使用新的JobScheduler.它与后台服务基本相同,但它会定期调用,而不是连续在后台运行.

如果您使用的是IntentService,则可以更改为JobIntentService.见@ kosev的answer below.

转载注明原文:Android 8.0:java.lang.IllegalStateException:不允许启动服务Intent - 代码日志