Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

前端 未结 17 1214
借酒劲吻你
借酒劲吻你 2020-11-22 09:15

On application launch, app starts the service that should to do some network task. After targeting API level 26, my application fails to start service on Android 8.0 on back

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:50

    Due to controversial votes on this answer (+4/-4 as of this edit), PLEASE LOOK AT THE OTHER ANSWERS FIRST AND USE THIS ONLY AS A LAST RESORT. I only used this once for a networking app that runs as root and I agree with the general opinion that this solution should not be used under normal circumstances.

    Original answer below:

    The other answers are all correct, but I'd like to point out that another way to get around this is to ask user to disable battery optimizations for your app (this isn't usually a good idea unless your app is system related). See this answer for how to request to opt out of battery optimizations without getting your app banned in Google Play.

    You should also check whether battery optimizations are turned off in your receiver to prevent crashes via:

    if (Build.VERSION.SDK_INT < 26 || getSystemService()
            ?.isIgnoringBatteryOptimizations(packageName) != false) {
        startService(Intent(context, MyService::class.java))
    } // else calling startService will result in crash
    

提交回复
热议问题