前言
本次主要内容包括:
1、Android8.0之后IntentService启动异常跟踪
2、JobIntentService替代IntentService方案
一、Android8.0之后IntentService启动异常跟踪
项目中在做启动优化时,在Application 通过IntentService启动第三方组件时,bugly时常会上报如下问题:
android.app.RemoteServiceException
Context.startForegroundService() did not then call Service.startForeground()
# main(2)
android.app.RemoteServiceException
Context.startForegroundService() did not then call Service.startForeground()
1 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2056)
2 android.os.Handler.dispatchMessage(Handler.java:106)
3 android.os.Looper.loop(Looper.java:192)
4 android.app.ActivityThread.main(ActivityThread.java:6959)
5 java.lang.reflect.Method.invoke(Native Method)
6 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:557)
7 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)
1、Service和IntentService使用场景以及区别
Service的使用场景:
a、Service是运行在主线程的,如果我们需要执行耗时操作,也是在Service创建Thread执行。
b、如果耗时操作无法在当前Activity生命周期执行完成的任务就需要在Service执行,比如异步下载等。
c、需要长时间在后台运行,跟随APP生命周期的任务需要在Service执行,比如Socket长连接。
d、Service是所有服务的基类,我们通常都是继承该类实现服务,如果使用该类,我们需要对Service的生命周期进行管理,在合适的地方停止Service。
IntentService特点
a、IntentService继承于Service,通过源码可以看到,是在Service的基础上增加了Handler、Looper、HandlerThread的支持;
b、只需要重写onHandleIntent(Intentintent)实现异步任务,这个方法已经是非UI线程,可以执行耗时操作;
c、一旦这个方法执行完毕,就会立刻执行stopSelf()停止服务,无需手动停止服务。
Android 8.0新增了startForegroundService方法,用于启动前台服务,前台服务是指带有通知栏的服务,如果我们使用startForegroundService启动服务,那么必须在5秒内调用startForeground()显示一个通知栏,否则就会报错
2、明明调用startforeground了为什么还会报Context.startForegroundService() did not then call Service.startForeground()
首先看下启动IntentService的调用: