HandlerThread继承自Thread,内部实现逻辑很简单,就是开一个消息处理线程,其run方法:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
以后我们只需要向这个mLooper发消息就会在这个子线程中处理了。
而IntentService里面就用到了HandlerThread,所以IntentService的关键方法onHandleIntent是运行在子线程中的。
看IntentService的onCreate方法:
@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 + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
这里创建一个mServiceHandler对象,它使用HandlerThread的mLooper作为Looper(消息处理器)。
IntentService的inStart方法:
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
显然这里发送了一个异步消息,注意onStart还是在当前线程中执行的,发送的消息会到ServiceHandler的handleMessage方法中:
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);
}
}
因此使用IntentService时需要去重写onHandleIntent方法,把处理逻辑放在该方法中,这样这些处理逻辑就会在子线程中执行了。
注意:从上面分析可知,对于IntentService,如果把处理逻辑放在onStartCommand(或者onStart)方法中运行的还是在调用线程中。
本博客已停止更新,转移到微信公众号上写文章,欢迎关注:Android进阶驿站