解决8.0,在后台启动服务闪退问题

在做保活机制的时候,一般在serviceonDestroy()方法中再一次启动服务,达到避免service被kill
先来看下报错对的日志(我的手机8.0的系统)

2019-07-10 15:31:31.049 16473-16473/com.scdx.vtalk E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.scdx.vtalk, PID: 16473
    java.lang.RuntimeException: Unable to stop service (XXXXX包名): java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.scdx.vtalk/(XXXXX包名) }: app is in background uid UidRecord{671a343 u0a249 SVC  bg:+1m0s13ms idle procs:1 seq(0,0,0)}
        at android.app.ActivityThread.handleStopService(ActivityThread.java:3633)
        at android.app.ActivityThread.-wrap26(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1732)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6701)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
     Caused by: java.lang.IllegalStateException: Not allowed to start service Intent {(XXXXX包名) }: app is in background uid UidRecord{671a343 u0a249 SVC  bg:+1m0s13ms idle procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1515)
        at android.app.ContextImpl.startService(ContextImpl.java:1471)
        at android.content.ContextWrapper.startService(ContextWrapper.java:654)
        at (XXXXX包名).onDestroy(SRV_KeepAlive.java:44)
        at android.app.ActivityThread.handleStopService(ActivityThread.java:3611)
        at android.app.ActivityThread.-wrap26(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1732) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:176) 
        at android.app.ActivityThread.main(ActivityThread.java:6701) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783) 

其中一句话就说明了问题所在
Not allowed to start service Intent { cmp=com.scdx.vtalk/(XXXXX包名) }: app is in background
大概翻译下来就是不允许在后台启动service Intent。
解决办法,

在service的onCreate()添加一段代码startForeground(1, mBuilder.getNotification());
mBuilderNotificationCompat.Builder,如果没有开启前台服务直接new Notification()也可以。

其次需要判断手机版本,在8.0以上的系统中才会遇到这类问题,

//8.0在后台需要调用新的方法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.startForegroundService(localIntent);
        }else{
            this.startService(localIntent);
        }

可以看看这个文章https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexceptio

你可能感兴趣的:(android)