Handler工作机制

本文和大家聊聊Handler工作机制这档子事。

什么是Handler?

官方定义:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

通俗的讲,咱们可以把Handler理解为Android中线程与线程间通信的工具。

Handler结构图

Handler如何工作?

咱们先来通过一个常见的场景,分析Handler是如何工作的。

第一步,咱们创建一个Handler实例,代码如下:

public Handler mHandler = new Handler(){
      @Override
      public void handleMessage(Message msg) {
          if(msg.what == GUI_UPDATE_TEXT) {
              String strValue = (String) msg.obj;
              mTextView.setText(strValue);
          }
      }
    };

第二步,咱们定义一个工作者线程,用来处理一些阻塞操作,代码如下:

class WorkerThread extends Thread{

        private Handler mHandler;

        public WorkerThread(Handler handler){
            mHandler = handler;
        }

        @Override
        public void run(){
            //do something

            Message msg = mHandler.obtainMessage(GUI_UPDATE_TEXT, strValue);
            mHandler.sendMessage(msg);
        }
    }

第三步,执行线程,开始干活,代码如下:

WorkerThread workerThread = new WorkerThread(mHandler); 
workerThread.start();

第一步中咱们创建了Handler,看似很简单明了的一个操作,其实Handler背后做了很多工作。

Handler被创建时,需要从当前线程中获取looper,并获取该looper中的消息队列(MessageQueue)。代码段如下:

// Handler源码
 public Handler(Callback callback, boolean async) {
       ...........
        mLooper = Looper.myLooper(); //获取当前线程的looper
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue; //获取looper中的消息队列
        .............
        .............
    }

第二步中线程执行完阻塞的事情后,会调动Handler的sendMessage,那sendMessage又做了什么呢?

sendMessage最终会调用sendMessageAtTime(是所有send方法的终点),sendMessageAtTime将消息(message)加入消息队列(MessageQueue)中,开始休息传递。代码段如下:

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis); //将消息加入消息队列
    }

到这里,咱们要传递的消息已经在消息队列中了,那是如何通知Handler的handleMessage的呢?

这就要谈到looper了,looper中有一个loop()方法,它会一直循环(不是轮询)检查消息队列中是否有可用的消息,若有可用的消息,则从消息中获取其所属的Handler,并调用Handler的dispatchMessage,由dispatchMessage将消息送达hanndleMessage。

Looper代码段如下:

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;       
        .................
        for (;;) {
            Message msg = queue.next(); // 获取可用的消息,此方法是阻塞的
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
        ...................         
            try {
                msg.target.dispatchMessage(msg);//获取message所属的Handler,调用其dispatchMessage
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
           ..................
           ...................
            msg.recycleUnchecked();
        }
    }

Handler代码段如下:

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

至此,主线程就可以执行UI更新,结束消息传递工作。

分析到这里,仍然有一些问题困惑着我们,例如:

  • Looper是如何与当前线程关联?
  • Handler的延时发送是如何实现?
    下面咱们来具体谈谈

Looper是如何与当前线程关联?

众所周知,Looper的初始化是通过调用prepare()方法,机敏的读者马上就会意识到,Looper与线程的关联一定与这个方法有关系。

没错,但是在讲解prepare方法之前,咱们先来看看ThreadLocal,因为它才是实现Looper与线程关联的核心元素。

ThreadLocal是线程的本地化变量,即只有拥有它的线程才可以访问,那它是如何做到这一点的呢?

ThreadLocal获取到当前线程对象,从该线程对象中获得ThreadLocalMap(即以ThreadLocal为key的map),并将自身放入到这个map,这样就完成了线程的本地化存储,即实现了只有拥有它的线程才可以访问。

ThreadLocal代码段如下:

 public void set(T value) {
        Thread t = Thread.currentThread();//获取当前线程对象
        ThreadLocalMap map = getMap(t);//从线程对象中获取ThreadLocalMap
        if (map != null)
            map.set(this, value);//若map中已经存在ThreadLocal,则放入自身和值(这里咱们假设值是Looper)
        else
            createMap(t, value);
}

咱们回到prepare()方法,该方法中将Looper存入threadlocal,完成Looper与当前线程的关联。Looper代码段如下:

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
 }

Handler的延时发送是如何实现?

延时消息发送的关键在MesaageQueue的enqueueMessage方法,需要延时发送的消息,在加入消息队列时,会根据当前消息的when值对整个消息队列进行升序排序,当when值超时,会被Looper获取到,从而完成延时消息的发送。

when值默认是系统启动到现在运行时间,不包含设备休眠的时间

下面咱们结合代码来看看:

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
          ......................
          ......................
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) { 
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // 当前消息的when < p.when,就将p放到当前消息的后面
                prev.next = msg;
            }
           .....................
           .....................
        }
        return true;
    }

我是青岚之峰,如果读完后有所收获,欢迎点赞加关注!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。