Handler源码解析

来源:互联网 发布:淘宝休闲斜挎包 编辑:程序博客网 时间:2024/05/20 19:31

这里先推荐大家一款查看源码的工具 :sourceinsight,大家自行google去下载。

大家都知道刚开始接触的Android的时候就接触了Handler,主要用来更新UI使用。在我的日常开发中,我感觉大多数场景下Handler确实是用来更新UI使用,其它地方也很少用到Handler,那么Handler到底是怎么来更新UI的呢?

首先我们先介绍几个类

Handler

我们看下源码中是怎么解释的

 A Handler allows you to send and process {@link Message} and Runnable  objects associated with a thread's {@link 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.
ok,我截了其中的一段来说明Handler的作用,文中的英文大概说的是 每一个Handler都与一个线程和这个线程的MessageQueue相关联,当你创建了一个handler,它将会负责传递messages ,并且会 runnables to that message queue ,然后执行那些要出队列的messages. 这个是我的个人理解,如果错误,请给我留言,谢谢!

这样的话,我们就可以大概的了解了Handler是干嘛的。

Handler里面持有了 MessageQueue 跟Looper两个对象。那么这个两个类是怎么来的呢?

源码中有这样一段:

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;    }
 这个是最清楚不过的了,MessageQueue是从Looper里面获取的,而mLooper是从Looper里面的myLooper函数拿到的。ok,等分析到Looper的时候我们再详细说,接着来看下handler里面主要的方法,sendMessage

public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }
层层调用之后会调用这个方法:

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }
发现了什么??queue,对吧,是不是清楚了发送消息是怎么一回事啊,就是通过这个队列的方式来存储跟发送消息的。

我们再看 handlermessage这个方法

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);        }    }
看到没用,handlerMessage方法是空的,当然了,这个是留给我们去实现的,但是,dispatchMessage,这个方法,里面调用了handlerMessage方法,那这个dispatchMessage方法是在哪里调用的呢??这里先告诉大家是在Looper里面调用的。

ok,  handler的主要代码我们先分析到这。接下来看MessageQueue.

MessageQueue

 Low-level class holding the list of messages to be dispatched by a * {@link Looper}.  Messages are not added directly to a MessageQueue, * but rather through {@link Handler} objects associated with the Looper. *  * <p>You can retrieve the MessageQueue for the current thread with * {@link Looper#myQueue() Looper.myQueue()}.
这是源码的解释。可以看出MessageQueue 跟Looper有着千丝万缕的关系。

 这个队列是通过底层c++来实现的,由于,我自己不了解c++,所以也没有往下面去深入,反正就记住这是个队列,有两个主要的方法,enqueueMessage跟next 方法,前者是用来入队,后者是用来出队的。enqueueMessage 这个方法前面说过是在handler里面调用的,而next方法是在Looper里面调用的,下面来看Looper


Looper

 Class used to run a message loop for a thread.  Threads by default do  * not have a message loop associated with them; to create one, call  * {@link #prepare} in the thread that is to run the loop, and then  * {@link #loop} to have it process messages until the loop is stopped.  *  * <p>Most interaction with a message loop is through the  * {@link Handler} class.  *  * <p>This is a typical example of the implementation of a Looper thread,  * using the separation of {@link #prepare} and {@link #loop} to create an  * initial Handler to communicate with the Looper.
  可以说,looper是整个handler机制的最核心的部分,简要的说下就是looper通过不断的循环获取queue里面获取message,然后通过msg.target.dispatchMessage方法,分发消息,在主线程中直接通过重写handMessasge方法,就可以处理消息了。那么msg.target是什么呢??前面有提到handler.sendmessage方法,我们来看下里面做了什么,
msg.target = this
哈哈,是不是非常清楚,message里面持有了Handler的引用。这个handler就代表了当前的handler。下面给出最核心的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();        }    }
就是一个死循环,不断的从队列里面取message,然后,再通过message的handler引用分发出去。

还没完,大家都知道,我在用handler的时候并没有去使用looper啊,那我这个是怎么串联起来的呢?来,别急,我们来看下程序的主入口main方法,main方法在ActivityThread 这个类里面,这个类就是Android程序的主线程了。

 public static void main(String[] args) {        SamplingProfilerIntegration.start();        // CloseGuard defaults to true and can be quite spammy.  We        // disable it here, but selectively enable it later (via        // StrictMode) on debug builds, but using DropBox, not logs.        CloseGuard.setEnabled(false);        Environment.initForCurrentUser();        // Set the reporter for event logging in libcore        EventLogger.setReporter(new EventLoggingReporter());        Security.addProvider(new AndroidKeyStoreProvider());        // Make sure TrustedCertificateStore looks in the right place for CA certificates        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());        TrustedCertificateStore.setDefaultUserDirectory(configDir);        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();        throw new RuntimeException("Main thread loop unexpectedly exited");    }}
 是不是很清晰,先是用Looper.prepareMainLooper方法,我们看下这个方法都干了些什么,

public static void prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }
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));    }
 public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }
这里用了一个ThreadLocal来保存Looper,相信大家都清楚这里为什么用ThreadLocal,主要是为了防止资源共享问题,为了保证一个主线程只有一个Looper对象。

大家看到没有,在ActivityThread的main方法中,调用了prepareMainLooper方法,拿到当前线程的Looper对象,然后再调用Looper.loop方法,不断循环。

到这,基本上,我就把这里面的代码分析完了,下面来介绍下两个大家常见的问题。

1.子线程更新UI问题。(可以是可以,但是是线程不安全的)

我们如果在子线程中更新UI会有什么问题,相信刚开始写Android的时候,都会遇到这样的问题

     Only the original thread that created a view hierarchy can touch its views
发生这样的异常的原因是在ViewRootImpl这个类里面,有这样一段代码

void checkThread() {        if (mThread != Thread.currentThread()) {            throw new CalledFromWrongThreadException(                    "Only the original thread that created a view hierarchy can touch its views.");        }    }
所以必须得先创建ViewRootImpl才能更新UI。具体方法就不介绍了,可以自行google

2.Android中为什么主线程不会因为Looper.loop()里的死循环卡死?

这里,我给出一个知乎上面讨论的链接,讲解的非常详细。https://www.zhihu.com/question/34652589。