IntentService 会自动开启子线程执行回调方法, 并且在任务执行完成之后调用stopSelf结束任务。
成员变量
// 子线程中创建的Looper
private volatile Looper mServiceLooper;
// 和Looper相关的Handler
private volatile ServiceHandler mServiceHandler;
onCreate方法
在onCreate方法中创建一个HandlerThread对象, 并启动该线程。之后取出和该Thread相关的Looper并构造一个ServiceHandler对象。
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类, 并调用start方法启动一个线程
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
// Looper在线程的run方法中构造, 获取的时候没创建会wait, 创建完成时notifyAll
mServiceLooper = thread.getLooper();
// 创建一个ServiceHandler对象
mServiceHandler = new (mServiceLooper);
}
HandlerThread类
继承自Thread类, 在run方法中创建Looper并调用Looper.loop进入事件循环
public void run() {
// 当前进程id
mTid = Process.myTid();
// 创建Looper
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
// 调用Looper.loop()
Looper.loop();
mTid = -1;
}
onStartCommand方法
利用ServiceHandler发送一条消息, ServiceHandler对应的Looper是子线程中的, Handler的handleMessage方法在子线程中执行
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
// 调用onStart方法
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
public void onStart(@Nullable Intent intent, int startId) {
// 利用mServiceHandler发送一条消息
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
ServiceHandler类
在handleMessage方法中完成对IntentService的onHandleIntent方法的回调
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// 子线程中执行IntentService的回调方法
onHandleIntent((Intent)msg.obj);
// 处理完之后调用stopSelf自动结束任务
stopSelf(msg.arg1);
}
}