上篇文章咱们讲日志的存储策略的时候用到了HandlerThread,它适合处理“多而小的任务”的耗时任务的时候,避免产生太多线程影响性能,那这个HandlerThread的原理究竟是怎样的呢?咱们如今从源码角度解读
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}复制代码
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);
}
}复制代码
在Service的onCreate()方法中实例化了一个ServiceHandler的对象:
面试
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);复制代码
实例化ServiceHandler对象的时候首先实例化一个HandlerThread,而后用HandlerThread对象的Looper实例化这个ServiceHandler,达到将二者绑定的目的,这样就能够经过ServiceHandler发送事件通知HandlerThread来执行了。
性能优化
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}复制代码
咱们看到在onStart方法中,把Intent传到msg中,而后使用serviceHandler发送消息给HandlerThread。
bash
在serviceHandler的handlerMessage方法中会调用咱们本身重写的onHandleIntent方法,最后结束本身。
同时咱们应该也能发现,必须执行OnCreate方法这个方法才能有效,因此启动这个服务的方法必须是startService,而不能是bind的方式。多线程
系列性文章,若是喜欢个人文章的点个赞和关注,你的赞和关注是我前行的动力架构