Handler源码分析

来源:互联网 发布:windows phone符号输入 编辑:程序博客网 时间:2024/06/06 13:21

对于Handler搞android的都熟悉,大概原理也知道,可能很多开发者也看过源码,本人也看过源码,但是一直没有系统的分析过,总结过,今天来一波对Handler的源码分析,本文需要读者了解handler的基本原理,如果不了解请参考Handler消息传递机制!

废话不在多说,直接开整!!!

看官:博主,从哪里开始分析呢?

博主:嗯,咱们就从Message message = Message.obtain();开始入手

然我们进入Message找到obtain方法:

/**     * Return a new Message instance from the global pool. Allows us to     * avoid allocating new objects in many cases.     */    public static Message obtain() {        synchronized (sPoolSync) {            if (sPool != null) {                Message m = sPool;                sPool = m.next;                m.next = null;                m.flags = 0; // clear in-use flag                sPoolSize--;                return m;            }        }        return new Message();    }

看官:博主,英文注释是啥意思?

博主:带我给各位翻译,意思:从全局消息池中返回一个实例,能使我们在很多情况下创建新对象(联想一下线程池)

在上面的代码中主要就是返回一个Message对象,但是这个对象并不是直接的创建出来的,而是先从Message Pool中去取,如果取不到,然后再创建,我们来分析一下主要代码:

if (sPool != null) {                Message m = sPool;                sPool = m.next;                m.next = null;                m.flags = 0; // clear in-use flag                sPoolSize--;                return m;            }

首先要明白,Message Pool其实是一个链表,其中每一个节点就是一个Message,sPool代表的就是第一个节点,在sPool不为空的时候,取出第一个节点赋值给m,注意接下来的动作就是把下一个节点弄成第一个节点,m.next就代表下一个节点,然后spool指向它,此时,第一个节点的指针还是m,第二个节点的指针是sPool,然后让m.next为null,目的是为了把第一个节点从链表中移除,让下一个节点成为真正的第一个节点,接着sPoolSize--代表此链表中的节点的个数少了一个,如果sPool减为0个,那次方法就会执行return new Message(),即创建一个Message对象。

好了,现在我们有消息了,然后我们就需要关注怎么把这个消息发送出去的代码了,发送消息的代码是在Handler对象中的,所以我们先来看看Handler.

通常我们实例化的都是无参数的Handler,我们来看此构造方法:

public Handler() {        this(null, false);    }

看官:我靠,这么简单!

博主:这叫代码少好不,那能叫简单,你能一眼看出这是啥意思?

我们接着进入this(null,false)中:

public Handler(Callback callback, boolean async) {        if (FIND_POTENTIAL_LEAKS) {            final Class<? extends Handler> klass = getClass();            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&                    (klass.getModifiers() & Modifier.STATIC) == 0) {                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +                    klass.getCanonicalName());            }        }        mLooper = Looper.myLooper();        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;    }

看官:我靠,有没有搞错,折磨长,确实不简单。

博主:别怕,我们只分析主要的代码

mLooper = Looper.myLooper();        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;

首先通过Looper.myLooper()得到一个轮询器,如果轮询器(Looper)为null,就会抛出一个异常"Can't create handler inside thread that has not called Looper.prepare()",异常的意思是说,因为没有调用Looper.prepare()所以不能再线程中创建handler,得到Looper之后,接着利用它得到消息队列。

我们知道了Looper是怎么取出来的,那我们是怎么存进去的呢?
我们先计入到myLooper()中:

/**     * Return the Looper object associated with the current thread.  Returns     * null if the calling thread is not associated with a Looper.     */    public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }

我们看到是通过sThreadLocal得到的,接着我们找一找是不是有set()方法。
还真有:

public void set(T value) {        Thread currentThread = Thread.currentThread();        Values values = values(currentThread);        if (values == null) {            values = initializeValues(currentThread);        }        values.put(this, value);    }

我们看看set方法在哪里被调用:
在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的时候不进行prepare就会抛出异常,原来这个方法的作用就是设置Looper,另外还有一点要注意,设置和取出Looper的时候,使用的是ThreadLocal,ThreadLocal的作用是在线程内是单例的,就是在同一个线程中,我们设置的Looper和取出的Looper是同一个。

这里顺便说一下,我们的消息队列是在哪里创建的呢?进入Looper中:

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

可以说,有了Looper,才有消息队列。

读者可能有疑问,说我在主线程中使用handler的时候,没有调用Looper啊,怎么不抛出异常呢?

这就需要看一看ActivityThread中的main()方法了:

public static void main(String[] args) {  SamplingProfilerIntegration.start();  CloseGuard.setEnabled(false);  Environment.initForCurrentUser();  EventLogger.setReporter(new EventLoggingReporter());  Process.setArgV0("<pre-initialized>");  Looper.prepareMainLooper();  ActivityThread thread = new ActivityThread();  thread.attach(false);  if (sMainThreadHandler == null) {      sMainThreadHandler = thread.getHandler();  }  AsyncTask.init();  if (false) {      Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));  }  Looper.loop();  //进行消息的轮询,为什么我们的主程序在不点击的时候也不会退出?就是因为有loop方法,内部是一个死循环。throw new RuntimeException("Main thread loop unexpectedly exited");  }  

发现有这样一行代码:Looper.prepareMainLooper();
我们进去看看:

/**     * Initialize the current thread as a looper, marking it as an     * application's main looper. The main looper for your application     * is created by the Android environment, so you should never need     * to call this function yourself.  See also: {@link #prepare()}     */    public static void prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }

哈哈,调用了prepare(false),原来主线程自动为我们调用了prepare,但是当我们在子线程中创建handler的时候,不要忘记调用prepare,子线程可不会为我们自动调用。

ok,接下来我们就可以研究最后一步了,就是怎么发消息的代码!

看官:发送消息的方法有很多啊,我们从哪一个说起呢?
博主:这位看官说的对,发送消息的方法确实有很多,但是,其实他们的内部用的是同一个方法发送的消息

public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }    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);    }    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {        Message msg = Message.obtain();        msg.what = what;        return sendMessageAtTime(msg, uptimeMillis);    }    public final boolean sendMessageDelayed(Message msg, long delayMillis)    {        if (delayMillis < 0) {            delayMillis = 0;        }        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);    }    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);    }

是不是发现了其实方法的内部都是通过sendMessageAtTime方法发送消息的。

那我们就分析这个方法:

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);    }

我们看到先得到一个消息队列(MessageQueue),如果不能得到这个消息队列,也就是queue==null,就会抛出异常,否则就会返回enqueueMessage(queue, msg, uptimeMillis),这个方法是什么功能呢?我们进去看看:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }

方法中的第一行代码:msg.target = this;,意思是把当前的类保存到msg中,当前类?对,当前的类就是一个handler,这句代码的含义就是把handler和msg联系起来,当处理的时候就用这个handler进行处理。
返回的结果就是把消息插入到消息队列中,具体的插入方法和链表的插入是一样的,为什么和链表的插入方式一样?我们前面不是说过了吗,消息队列其实是一个链表。
由此看出,其实发送消息就做了一件事,就是把消息插入到消息队列。

现在消息队列中已经有消息了,我们现在既可以取出消息进行处理了,怎么取出消息呢,用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 (;;) {            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.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();        }    }

看官:我靠,折磨复杂?
博主:仔细看看好不好,一看长就说复杂,哎

分析以上代码,它先执行Looper me = myLooper();得到Looper,然后又通过MessageQueue queue = me.mQueue;得到消息队列,然后就是一个死循环

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

用来获得消息,接下来又有一句这样的代码msg.target.dispatchMessage(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);        }    }

我们看到有这样的代码:

if (msg.callback != null) {            handleCallback(msg);        }

我们很好奇,这个callback是什么玩意,这个其实就是一个Runnable,还记得我们使用handler的时候,handler有一个post方法:

public final boolean post(Runnable r)    {       return  sendMessageDelayed(getPostMessage(r), 0);    }

此方法传入一个Runnable参数,然后我们进入getPostMessage(r)中:

private static Message getPostMessage(Runnable r) {        Message m = Message.obtain();        m.callback = r;        return m;    }

这就不解释了,相信大家都能看懂。

回到dispatchMessage方法,我们分析一下他,首先如果我们向消息队列中插入一个Runable就会执行handleCallback(msg);方法,其实就是一个run方法,否则就会判断mCallback != null是否为空,mCallback是什么呢?这其实是一个接口,我们知道handler还有一种使用方法,就是

 Handler.Callback callback = new Handler.Callback() {        @Override        public boolean handleMessage(Message msg) {            return false;        }    };    Handler handler = new Handler(callback){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);        }    };

这种处理消息的方式,按照dispatchMessage方法的逻辑,上面的那个方法会处理消息?看else中的代码:

if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);

如果有handler.callback的时候,会优先调用mCallback中的处理消息方法。

最后对dispatchMessage方法做一个总结,就是当传入的是Runnable的时候,先处理Runnable,否则判断是不是有Callback,如果有就先处理它,如果没有或者没有处理,那就在自己覆写的handleMessage方法中处理消息。

OK,Handler基本原理大概就分析完了,多谢大家收看!

如有错误,敬请指出,不胜感激!

2 0
原创粉丝点击