作用:可执行耗时操作的Service。
优点:一个后台线程是很容易被系统杀死的,优先级非常低。而IntentService是一个服务,不容易被系统杀死。
源码分析:
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start(); // 开启子线程,初始化Looper
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper); // 构建Handler
}
- 在IntentService的onCreate()方法中,创建了一个HandlerThread。
- HandlerThread是一个线程在run()方法中实现了Looper的初始化操作,因此通过thread.getLooper()获取到HandlerThread的looper。
- 用HandlerThread的looper构建一个ServiceHandler
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj); // 执行耗时操作
stopSelf(msg.arg1); // 等待所有消息处理完后终止服务,在onDestroy()中退出looper,终止子线程操作
}
}
- ServiceHandler内部通过handleMessage()获取到msg,执行onHandleIntent()的内容。
- 从代码可见onHandleIntent()是一个抽象方法,在此可进行耗时任务的操作。
- stopSelf(msg.arg1);在完成任务后关闭服务回调IntentService的onDestroy(),执行mServiceLooper.quit(),从而终止mServiceLooper所在的子线程即我们在onCreate()方法中创建的子线程HandlerThread
另外,只有通过startService()才会触发onStartCommand()生命周期,调用onStart(),完成消息的发送即子线程中任务的转换。
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}