Android Handler详解--理论篇

来源:互联网 发布:java实现rsa算法 编辑:程序博客网 时间:2024/05/18 02:24

概述

在平时的开发中,我们一般会在子线程请求数据,因为Android的UI操作不是线程安全的,所以我们会有切换到UI线程(主线程)更新UI的需求。有以下两种方法:

  • 使用Activity的runOnUiThread方法。
  • 使用Handler。

其实查看源码就能发现runOnUIThread方法还是基于Handler的,接下来就详细解析Handler机制。

相关类

Handler机制其实是Handler、MessageQueue、Looper三个类共同作用的结果,只是我们经常和Handler打交道所以对Handler比较熟悉。

MessageQueue

这个类相对简单,维护一系列的Message,有两个主要方法

  • boolean enqueueMessage(Message msg, long when)
  • Message next()

enqueueMessage将一条消息入队,next方法返回队头的一条消息,并将该条消息出队,需要注意的是如果消息队列为空,那么这个方法就会阻塞直到有消息入队。

Looper

每个线程都有自己的Looper实例,通过Looper.myLooper()获得当前线程的Looper实例,这是通过ThreadLocal实现的,如果不知道ThreadLocal的点这。
Looper的作用就是无限循环从MessageQueue中拿消息,拿到消息之后调用方法(后面会讲到)。

先看看Looper类的变量

    // sThreadLocal.get() will return null unless you've called prepare().    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();    private static Looper sMainLooper;  // guarded by Looper.class    final MessageQueue mQueue;

除了主线程默认有Looper外,其余的线程若想使用必须调用Looper.prepare()初始化当前线程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的构造方法

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

可以看出一个Looper持有一个自己的MessageQueue,而且一个线程只会有一个Looper,也就是一个线程一个MessageQueue。

接下来就是最重要的方法了–Loop.loop(),先看看代码

    public static void loop() {        ......        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);                }            }            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();        }    }

可以看出是在一个死循环中从队列取出消息,然后调用msg.target.dispatchMessage(msg)处理消息。其实仔细看会发现如果返回null,那么就会跳出死循环,那么什么时候queue.next()会返回null呢?当Looper的quit被调用的时候,他就会调用queue的quit,这样queue就会返回null,从而达到退出loop的目的。

Handler

Handler作用就是发送消息和处理消息,当一个Handler创建的时候,他就会和当前线程的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;    }

在构造方法中得到当前线程的Looper和MessageQueue,并保存起来。重头戏在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);    }

可以看出这里就将消息放入队列了,然后Looper一直在循环消息队列,这个时候他就拿到一条消息,然后调用msg.target.dispatchMessage(msg)处理消息,我们看一下Message的结构

/**     * User-defined message code so that the recipient can identify      * what this message is about. Each {@link Handler} has its own name-space     * for message codes, so you do not need to worry about yours conflicting     * with other handlers.     */    public int what;    /**     * arg1 and arg2 are lower-cost alternatives to using     * {@link #setData(Bundle) setData()} if you only need to store a     * few integer values.     */    public int arg1;     /**     * arg1 and arg2 are lower-cost alternatives to using     * {@link #setData(Bundle) setData()} if you only need to store a     * few integer values.     */    public int arg2;    /*package*/     Handler target;

可以看出每一条消息都有一个target变量,代表发送他的Handler,而且以后处理消息也是这个Handler,那这个target是在哪里赋值的呢?其实是在sendMessageAtTime中的enqueueMessage()方法

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

梳理流程

每个类的原理都讲明白了,接下来我们整理一下他们的关系。一个线程只有一个Looper,一个Looper内部维护着一个MessageQueue,创建Handler的时候,该Handler自动和当前线程的Looper关联起来。
当使用该Handler发送消息的时候,使用Handler关联Looper的MessageQueue将消息入队,然后Looper无限循环查询消息队列,一有消息就处理,处理方式是通过调用该Message的target的handleMeessage方法。

线程切换

大概流程就是这样,但是可能有人还是很迷糊,那到底是怎么样实现线程的切换的?
我们一步一步来看,如果我们的Handler在主线程创建,那么关联的就是主线程的Looper,到最后调用的handleMessage的就是这个Looper,那么该方法就肯定在主线程运行了。而在子线程中,我们做的只不过是发送消息,也就是改变主线程的消息队列,然后主线程的Looper拿到消息处理,这样就实现了线程转换。

下一篇我们会自己实现一个Handler加深对Handler机制对理解,而且还涉及到Android程序启动的流程,有兴趣的朋友可以看一眼。
Android Handler详解–实战篇

0 0
原创粉丝点击