Android进阶:2、从源码角度看透 HandlerThread 和 IntentService 本质

上篇文章咱们讲日志的存储策略的时候用到了HandlerThread,它适合处理“多而小的任务”的耗时任务的时候,避免产生太多线程影响性能,那这个HandlerThread的原理究竟是怎样的呢?咱们如今从源码角度解读
  • HandlerThread:继承自Thread,是一个可使用Handler的Thread。由于在run方法内维护了一个Looper,能够经过Handler发送消息的方式,来通知HandlerThread执行一个具体的任务。

public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }复制代码

  • IntentService是HandlerThread的一个具体的使用场景。首先内部封装了一个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);
        }
    }复制代码

在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的方式。多线程

系列性文章,若是喜欢个人文章的点个赞和关注,你的赞和关注是我前行的动力架构

最后送福利了,如今关注我而且加入群聊能够获取包含源码解析,自定义View,动画实现,架构分享等。
内容难度适中,篇幅精炼,天天只需花上十几分钟阅读便可。
你们能够跟我一块儿探讨,欢迎加群探讨,有flutter—性能优化—移动架构—资深UI工程师 —NDK相关专业人员和视频教学资料,还有更多面试题等你来拿~

群号:925019412

相关文章
相关标签/搜索