Handler 源码解析

Handler作为android常用线程之一, 能够在线程里处理耗时操作,并通过发送Message的方式,更新UI。注意:android不允许在非UI线程更新U,为了能在子线程也就是非UI线程执行完后,能执行UI操作,封装了Handler。因此,学习Handler的运行机制,很有收益

提及Handler , 不能避谈Message和Looper, 他们三者相互协作,构成了Handler的运作方式。下面看源码:

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;
    }
public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
final Looper mLooper;
final MessageQueue mQueue;
final Callback mCallback;

Handler共有7个构造函数,这里截取了2个构造函数,因为其他的构造函数最终都会运行到这两个构造函数之一,也就说是,这两个构造函数才是真正初始化了Handler。

在构造函数里可以看到 , Hanlder保存了Looper的引用,并且在“mQueue = looper.mQueue”关联了Looper里的MessageQueque

再来看Looper

final MessageQueue mQueue;
final Thread mThread;

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

Looper在构造函数里构造了消息队列MessageQueue (即在Handler被引用的那一个) , 但是注意到,它的构造函数是私有的,那么Looper()在什么时候被调用呢?

/**
     * 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();
        }
    }
public static void prepare() {
        prepare(true);
    }

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

从注释中可以看到,android应用会自动调用prepareMainLooper()创建一个Looper,而prepareMainLooper()调用了prepare()实例化了Looper。在此 ,Looper就创建好了。

紧接着来看看Looper的运转

**
     * 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();
        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.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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() 是Looper的要点,在这个函数里,有一个无限循环,在这个循环里,代码 Message msg = queue.next() 不断消息队列里取出 Message,然后尝试调用 msg.target.dispatchMessage(msg)。这似乎就是loop()主要做的事情,而loop()又是Looper的核心运转方式,那么不禁要问msg.target.dispatchMessage(msg)是什么?

先别着急,我们可以看到msg是个Message,那么我们只有去Message里找答案,下面是Message的源码:

/*package*/ Handler target;

public static Message obtain(Handler h, int what) {
        Message m = obtain();
        m.target = h;
        m.what = what;

        return m;
    }

找到了这些代码,原来target是一个Handler,在obtain方法里关联了一个Handler ,也就是说dispatchMessage调用的是Hanlder里的方法。 (还有其他的obtain , 在此不引入)

那么在这里似乎就清晰了,Looper 在loop 从MessageQueue不断获取Message ,然后调用msg.target.dispatchMessage(msg),也就是调用Handler里的方法给予Handler反馈,让Handler处理。

那Hanlder是不是这样运转呢? 回到Hanlder看看Hanlder的源码

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

public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

Handler里的这三个函数常用的三个发送消息的函数,可以看到,他们都会调用sendMessageDelayed(),这里似乎还有信息,接着往下找

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

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

经过层层调用,sendMessageDelayed()到达了enqueueMessage() , 在这里,msg.target = this 将当前handler关联到了即将发送的Message里,然后将Message加入到了MessageQueue,可见,和我们猜想的一样。

到这里,还没有结束,我们知道了Handler关联了Looper的MessageQueue,并在讲Message加入到MessageQueue的时候,Message.target 为此Hanlder 的引用。且在Looper不断从loop里获取Message然后调用了Handler里的dispatchMessage, 我们有必要去看看这个函数

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

在dispatchMessage()里, 调用到了 handleMessage(msg)

/**
 * Subclasses must implement this to receive messages.
 */
 public void handleMessage(Message msg) {
 }

是不是很眼熟? 没错,handleMessage()就是我们在创建Handler的时候覆盖的那个函数。就是说,在线程处理事件后,在线程里通过Hanlder发送了消息,然后Handler在UI线程里通过handleMessage()接收发送的消息,然后可以进行UI相关操作,由此,就解决了子线程不能更新UI的问题。

到此,代码解析完毕

流程图
(不是规范作图)

这里写图片描述

总结

1、Hanlder在初始化时,会关联Looper的MessageQueue
2、Looper由Android自动初始化,维护一个MessageQueue
3、Hanlder在需要的时候,向MessageQueue发送Message,并在Message的target变量里引用了此Hanlder
4、Looper在loop()里不断从MessageQueue获取Message , 当获取到了Message的时候,尝试调用msg.target.dispatchMessage(msg)
5、Handler在UI线程里接收dispatchMessage() , 并在创建时覆盖了该函数,在改函数里执行了UI操作

此文章旨在做个人笔记使用,如果错误地方欢迎指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值