1、service 的生命周期,两种启动方式的区别
startService()和bindService(),
参考文章:
bbs.huaweicloud.com/blogs/28808…
2、Service的启动流程
参考文章:
gityuan.com/2016/03/06/…
3、Service与Activity怎么实现通信
bindService()的方式,Activity持有对应的binder来调用service里面的方法。
广播通信。
参考文章:
blog.csdn.net/weixin_4110…
4、IntentService是什么,IntentService原理,应用场景及其与Service的区别
在Android 8 或者更高的版本上,考虑不再使用IntentService,可以使用workManager和JobIntentService来替代。 Service是在主线程里面,如果要做耗时操作,需要开个子线程。IntentService在onCreate的时候会初始化一个HandlerThread,可以直接在onHandleIntent里面直接做耗时操作。
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); //初始化一个HandlerThread
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@WorkerThread //在工作线程
protected abstract void onHandleIntent(@Nullable Intent intent);
参考文章:
www.codetd.com/article/107…
5、Service 的 onStartCommand 方法有几种返回值?各代表什么意思?
有四种返回值:
- START_STICKY: 如果 service 进程被 kill 掉,保留 service 的状态为开始状态,但不保留递送的 intent 对象。随 后系统会尝试重新创建 service,由于服务状态为开始状态,所以创建服务后一定会调用 onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到 service,那么参数 Intent 将为 null。
- START_NOT_STICKY: “非粘性的”。使用这个返回值时,如果在执行完 onStartCommand 后,服务被异常 kill 掉,系统不会自动重启该服务。
- START_REDELIVER_INTENT: 重传 Intent。使用这个返回值时,如果在执行完 onStartCommand 后,服务被异 常 kill 掉,系统会自动重启该服务,并将 Intent 的值传入。
- START_STICKY_COMPATIBILITY: START_STICKY 的兼容版本,但不保证服务被 kill 后一定能重启。
@IntDef(flag = false, prefix = { "START_" }, value = {
START_STICKY_COMPATIBILITY,
START_STICKY,
START_NOT_STICKY,
START_REDELIVER_INTENT,
})
public @StartResult int onStartCommand(Intent intent, @StartArgFlags int flags, int startId) {
onStart(intent, startId);
return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
}
参考文章:
segmentfault.com/a/119000004…