1、基本概念
Service:service作为Android的四大组件之一,它可以用于在后台执行所谓的耗时操作。
但是耗时操作实际上也不能在service的主线程中去操作,因为前台的service,20s超时。后台的service 200s超时。
实际上还是在service的onStartCommand的开子线程去做耗时操作。
有文章说可以使用service做一些宿主被销毁后,依然想继续执行完子线程中任务的操作。不否认这样是可以的。
从宿主销毁但是service不被销毁,我们可以得出当前的service是被startService()起来的。
宿主的回收没有将service释放,实际上这个service可以理解一直在游离状态,直到下一次触发GC被GC回收(宿主不主动stop的情况下)。
IntentService:
IntentService 是继承于 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作,启动 IntentService 的方式和启动传统 Service 一样,同时,当任务执行完后,IntentService 会自动停止。
@Override
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 + "]");
(1)thread.start();
//获取子线程的looper,可以参考下具体实现(2)
mServiceLooper = thread.getLooper();
// 创建一个子线程的handler.值得说明的是正常情况下在子线程中创建handler是会抛异常的。要求在创建前先Looper.prepare()。
// 为什么当前不会抛异常
// 注意HandlerThread的start(),实际在start的时候是触发thread的run方法。这个时候就开始调用Looper.prepare();
mServiceHandler = new ServiceHandler(mServiceLooper