【源码解读】Handler消息机制流程分析

来源:互联网 发布:淘宝模特拍摄 编辑:程序博客网 时间:2024/06/06 01:38

之前看《艺术探索》大致了解了Android消息机制的原理,也总结了笔记,但总感觉理解的不够彻底,之后把源码和之前的笔记又看了一遍,算是基本通了,将基本逻辑记录在此,重在分析流程,不分析具体细节原理。

这里以主线程为例,Handler消息机制的完整过程如下:

1.线程创建Looper, 同时初始化MessageQuene和Thread对象,开启循环

在ActivityThread的main方法中,会首先创建主线程的Handler,因此我们在主线程中是可以创建Handler对象而不需要考虑Looper问题的。

 public static void main(String[] args) {    //代码省略...    Looper.prepareMainLooper();    Looper.loop(); }

最终通过prepare方法创建Looper对象并使用ThreadLocal进行存储,源码如下:

public static void prepareMainLooper() {    prepare(false);    synchronized (Looper.class) {        if (sMainLooper != null) {            throw new IllegalStateException("The main Looper has already been prepared.");        }        sMainLooper = myLooper();    }}//最终调用该方法创建Looer对象,因为是主线程所以这里的参数为falseprivate 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的构造函数中会同时创建其MessageQuene和Thread对象.这样就创建好了我们需要的Looper对象以及MessageQueue和Thread对象,并通过Looper.loop()方法开启无限循环

private Looper(boolean quitAllowed) {    mQueue = new MessageQueue(quitAllowed);    mThread = Thread.currentThread();}

2.创建Handler对象

这里最常使用的方式就是新建一个Handler对象并传递一个CallBack对象,当然还有其他的构造方法,这里不作赘述

    private  Handler handler = new Handler(new Handler.Callback() {        @Override        public boolean handleMessage(Message msg) {            switch (msg.what){                case 1:                    String obj = (String) msg.obj;                    Log.i(TAG, obj);                    break;            }            return true;        }    });

3.sendMessage或者post一个Runnable对象

使用创建好的handler对象传递消息,无论是sendMessage还是post一个Runnable对象,最终会调用到
sendMessageAtTime,之后会调用MessageQuene对象的enqueueMessage()方法将消息加入到队列中

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); }    //设置msg.target为当前Handler对象,并将消息存储进消息队列  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }

4.在loop方法中,调用handler的dispatcher进行分发.

在prepare好Looper之后,便调用了loop方法,其源码如下

  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 (;;) {            /**            * 调用MessageQuene的next方法获取消息对象,如果没有消息则终止循环            */            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            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            /**            * msg.target就是在enqueueMessage方法中设置好的Handler对象,            * 调用dispatchMessage进行消息分发            */            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycleUnchecked();        }    }

loop内部也是无限循环,去调用MessageQuene的next方法,如果有消息则拿到消息对象并通过Handler对象进行分发进行分发

5.dispatchMessage对消息进行分发,根据传递的消息选择不同的调用,具体如下

   public void dispatchMessage(Message msg) {        if (msg.callback != null) {        //检查Message的callback是否为空,不为空则调用handleCallback        //当我们使用post提交一个Runnable对象的时候回调用该方法,最终执行我们        //的Runnable对象的run方法中的内容            handleCallback(msg);        } else {            if (mCallback != null) {                //当使用sendMessage发送信息并创建了CallBack对象时调用                //这就是我们最常见的使用方法,最终会调用到我们重写的handleMessaeg方法                if (mCallback.handleMessage(msg)) {                    return;                }            }            //调用Handler自己的handleMessage,方面里面为空,啥都不干            handleMessage(msg);        }    }

简单来说,在子线程通过主线程的Handler对象发送数据时,最终会调用到Handler的handleMessage方法进行处理,因为Handler处于主线程,那么此时操作就从子线程切换到了主线程,从而线程间的通信。

OK,以上就是整个Handler消息机制的创建处理流程。

0 0
原创粉丝点击