handler 机制源码分析

handler机制:

概念

 handler机制是一种异步通信机制,通常用于子线程中数据更新后,通知主线程UI更新。

handler运行框架图

《handler 机制源码分析》

运行

 从上面handler的运行框架图来看,为了完成handler整个流程,你必须按事先创建好四个东西:
 handler、Message、MessageQueue和Looper,也许Looper从上图来看并不是必须的,因为遍历MessageQueue只是调用了一个静态方法而已,并没有实例化一个Looper对象,既然这么想,那我们看看Looper.Loop()源码就知道了:
    /** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */
    public static void loop() {
        final Looper me = myLooper();     //获取了一个Looper对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ........
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            .......
            msg.recycleUnchecked();
        }
    }
上面第6行代码就会获得一个Looper实例,所以你还需要一个Looper实例的,那么你就会有一个疑问了,Looper对象哪里创建的呢?解决的办法就是跟踪源码myLooper()
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

上面代码就是利用ThreadLocal获取一个局部变量ThreadLocal,而这个局部变量也是在ThreadLocal.set(Object)设置进去的,那么又是在哪个地方设置进去的呢,继续跟踪代码,经过一番查找,我们在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));
    }
对,没错,就是这个方法;这个方法创建Looper对象;并且可以看出:ThreadLocal局部变量一经设置后就不允许再次设置,所以这个方法只能在同一个线程里面只能调用一次

跟踪到这里,Looper算是弄明白了,不难总结出,Looper这个对象必须要在handler发送消息之前就事先创建好,并且也只能创建一次,不然你使用Looper.Loop()无法进行消息遍历的,但是通常我们在Activity里面使用Handler的时候,并没有调用Looper.prepare()去创建Looper,这是怎么回事呢?
 答案就是:Activity通常是在UI线程中,但却不是UI线程的入口,UI线程入口是ActivityThread.main()这里,这个类里面帮我们去创建了Looper,查看源码就可以知道:

public static void main(String[] args) {
        …………

        Looper.prepareMainLooper();             //创建Looper并ThreadLocal.set(Looper)绑定

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {      //创建handler
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();                        //looper遍历队列

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
从这儿我们就可以看出handler的执行步骤了:
1. 创建Looper   --- Looper.prepare()
2. 创建Handler对象 --- new handler
3. 遍历队列  --- Looper.loop()

总结: UI线程中,你只需要执行第二步就可以了,如果是在非UI线程,你就必须三步都执行才行

handler的使用流程,已经分析清楚了。
但是内部如何发送、Looper怎么遍历以及如何接受消息并处还不是很清楚,下面继续分析来搞明白这些问题:

创建Looper

这个好理解,不管是UI线程还是非UI线程,最终都会去调用prepare()方法去new Looper()对象,那这个Looper对象里面有什么东西呢?看源码了解下:
final MessageQueue mQueue;
final Thread mThread;
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
 Looper里面创建了MessageQueue和上面的连接起来了,Looper里面创建了MessageQueue,这个队列是一个链表结构的队列

Handler

handler用法我们一般是下面这两种方式来使用:
private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            //your code
        }

    };
        handler.sendEmptyMessage(0);              //send方式
        handler.post(new Runnable() {            //post方式

            @Override
            public void run() {
                //your code
            }
        });
先看第一种send方式,源码:
public final boolean sendEmptyMessage(int what) {
        return sendEmptyMessageDelayed(what, 0);
    }
这个好理解,继续:
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
这里,我们发现即使发送空的Message,Handler都会主动去创建Message,并且自行携带一个延时参数;
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
SystemClock.uptimeMillis()表示开机到现在的毫秒数,不包括睡眠时间,这里为什么要使用这个时间而不是用System.currentTimeMillis(),暂时我也无法理解,可能是因为handler通信有阻塞的关系?
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);  //消息入队
    }
到这里也印证上面,如果你之前没有创建好Looper就直接使用handler,在这个方法里面就会跑出空队列MessageQueue的异常,mQueue是Handler的成员变量,这个变量在handler的构造方法里面通过Looper获取的
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
这里就会给Message的target赋值thisthis就是指你发送的这个handler,后面的enqueueMessage就是消息入队了:
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) {    //同步
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;                //完整封装Message
            Message p = mMessages;          //消息的头节点
            boolean needWake; 
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue. Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;   
                for (;;) {    //根据延时插入消息队列
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
1)首先判断消息的接收者是否赋值,如果没赋值消息就不知道发给谁了
(2)when值封装到Message里面去
(3)插入消息队列,根据延时长短插入进去,队列按照延时由短到长排列,最后消息取出来的时候也是先取短的,后取长的

到这步send方式的就完成了,post方式的情况和send方式大同小异,就是签名的消息封装不一样

 public final boolean post(Runnable r) {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

private static Message getPostMessage(Runnable r, Object token) {
        Message m = Message.obtain();
        m.obj = token;
        m.callback = r;
        return m;
    }
//
post方式底层也会产生一个Message,并把Runnable赋值给Message.callback对象,后面的sendMessageDelayed和send就是一样的了

handler发送总结:
(1)使用Handler之前一定要创建Looper对象
(2)new Handler的构造方法会去拿第一个步骤创建的Looper和MessageQueue
(3)send和post方式底层都会封装Message,只是Message内部成员赋值不同而已
(4)最终都会调用底层的sendMessageAtTime(msg,when)
(5)进入消息队列,根据延时when的长短

Looper.loop()遍历队列

//Looper.java
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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

          …………

            msg.recycleUnchecked();
        }
    }
(1)queue.next()遍历取消息,这是一个阻塞方法
(2)取出消息后msg.target.dispatchMessage(msg)发送消息,target也就是之前在发送的时候设置的

接收Message并处理

public void handleMessage(Message msg) {
    }

    /** * Handle system messages here. */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
 从上面可以看出最终执行的有三种方式:
 (1handleCallback(msg);  这种方式就是我们使用post的方式
 (2mCallback.handleMessage(msg)   这种方式是我们使用Handler构造方法传递Callback方式使用的:
 例如:public Handler(Looper looper, Callback callback, boolean async)
 (3handleMessage(msg);  最后这种就是我们在Activity写匿名内部类的时候用的,重写了handleMessage(msg)方法的

至此,handler的发送到接收方式就分析完了,如有错误,还请指正!
Android相关源码在此:
github.com/android/pla…

    原文作者:Android源码分析
    原文地址: https://juejin.im/entry/5902bebd1b69e60058c57b5e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞