HandlerThread 与 IntentService 源码分析

来源:互联网 发布:ubuntu软件中心下载 编辑:程序博客网 时间:2024/05/22 06:28
HandlerThread 是线程类,主动绑定 Looper ,为 Handler 提供了消息队列,IntentService 中通过为 Handler 绑定 HandlerThread 提供的子线程 Looper,从而使 Handler 处理消息在子线程,由于 Looper 是死循环,所以在 IntentService 销毁时,必须停止 Looper 中消息队列的循环 MessageQueue.quit() ,从而停止 HandlerThread。

HandlerThread 原理解析

继承了 Thread 类,是一个线程类,在 run() 方法中 调用了 Looper.prepare() 和 Looper.loop() 方法,所以该线程默认已经绑定了 Looper ,还提供了获取绑定的 Looper 对象的方法 getLooper(); 调用该方法时如果 Looper 没有初始化则调用该方法的该线程会 wait() 等待,Looper 对象绑定之后则会 notifyAll(); 唤醒所有 wait() 的线程,从而保证了 getLooper() 方法会得到正确的 Looper 对象。 获取到 Looper 之后就可以创建与该子线程绑定的 Handler ,通过 Handler 就可以发送消息,从而在子线程中处理消息。

HandlerThread 的 run 方法为一个死循环,终止运行 使用 quit 方法和 quitSafely 方法,两个方法的区别是 MessageQueue 消息队列中对消息的处理, quit 方法中直接回收每一个消息,quitSafely 中会将大于当前时间的未处理消息直接回收,对已经开始执行的消息,会安全回收

HandlerThread 存在意义

HandlerThread 作为一个线程对象,其存在意义为,提供了一个绑定到子线程的 Looper ,从而得到在子线程中轮询的消息队列, 从而可以初始化时 Handler 绑定的消息队列为子线程。

@Overridepublic void run() {    mTid = Process.myTid();    Looper.prepare();    synchronized (this) {        mLooper = Looper.myLooper();        notifyAll();  // 唤醒 wait() 的线程    }    Process.setThreadPriority(mPriority);    onLooperPrepared();    Looper.loop();    mTid = -1;}public Looper getLooper() {    if (!isAlive()) {        return null;    }    // If the thread has been started, wait until the looper has been created.    synchronized (this) {        while (isAlive() && mLooper == null) {            try {                wait(); // 等待 Looper 对象创建            } catch (InterruptedException e) {            }        }    }    return mLooper;}

IntentService

  1. 继承了 Service 类,是服务。使用时需要重写其内部的抽象方法 onHandleIntent() ;
  2. 在 onCreat() 方法中创建了 HandlerThread 对象,通过调用 HandlerThread 对象的 getLooper() 方法得到了子线程的 Looper 对象;
  3. 接着通过该 Looper 对象创建了内部类 ServiceHandler 的对象,该 ServiceHandler 处理消息时在 HandlerThread 线程中。
  4. 接着在 onStart() 方法中,调用 ServiceHandler 的 obtainMessage() 方法创建了一个 Message 对象,该方法是 Handler 中的方法,实现是通过调用 Message.obtain(); 方法创建 Message 对象,obtain() 方法需要一个 Handler 对象,传入 ServiceHandler 本身即可。创建 Message 对象后,使用 ServiceHandler 将消息发送出去。
  5. ServiceHandler 发送消息后,根据消息处理机制 ServiceHandler 会收到该消息,此时即调用重写的 IntentSErvice 的 onHandleIntent() 方法,在 子线程(ServiceHandler 中的 HandlerThread) 中处理消息。
  6. 最终实现了 Service 运行在子线程。
  7. 处理完消息后调用了 stopSelf(int id) 方法,之所以没有调用 stopSelf() 方法是因为,如果没有参数,会直接停止该 Service,由于 Service 可能被启动多次,所以调用 stopSelf 带参数的方法,只有当参数 id 同启动 Service 的次数相同是 Service 才会停止,因为消息队列中的消息是依次处理的,所以最后一个处理结束后,调用 StopSelf 带参数的方法会正常停止 Service
  8. 在 IntentService 的 onDestory 方法中执行了 mServiceLooper 的 quit 方法,停止 HandlerTreand 中 Looper 的死循环,从而安全的退出 HandlerThread 线程。

ServiceHandler (继承了 Handler 类,是一个 Handler类,其 handleMessage() 方法调用了 IntentService类 的一个抽象方法 onHandleIntent() 来处理消息。处理完成之后就会自动结束)

public abstract class IntentService extends Service {    /**     * 内部类 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);        }    }    @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);    }    @Override    public void onStart(@Nullable Intent intent, int startId) {        Message msg = mServiceHandler.obtainMessage();        msg.arg1 = startId;        msg.obj = intent;        mServiceHandler.sendMessage(msg);    }    protected abstract void onHandleIntent(@Nullable Intent intent);    @Override    public void onDestroy() {        mServiceLooper.quit();    }}

IntentService 是一个抽象的服务类,使用时只需要新子类继承 IntentService 并重写其抽象方法 onHandleIntent() 调用类其对象的 start() 方法之后,则在子线程中执行 onHandleIntent() 中的代码。

原创粉丝点击