电脑基础 · 2023年3月15日

service启动的正确姿势

  1. E FATAL EXCEPTION: main

Process: com.neusoft.controlboard, PID: 14833

java.lang.RuntimeException: Unable to create service com.neusoft.controlboard.BoardService: java.lang.IllegalStateException: Not allowed to start service Intent { act=xxx.service pkg=xxx }: app is in background uid null

at android.app.ActivityThread.handleCreateService(ActivityThread.java:4198)

at android.app.ActivityThread.access$1500(ActivityThread.java:237)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)

at android.os.Handler.dispatchMessage(Handler.java:106)

at android.os.Looper.loop(Looper.java:223)

at android.app.ActivityThread.main(ActivityThread.java:7664)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { act=xxx.service pkg=xxx }: app is in background uid null

如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException。

新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

android 11startForegroundService无法启动其他应用service

添加权限 <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>