Android中的Handler机制


还记得第一次使用Handler的情形,我开启了一个子线程,在子线程中给TextView进行setText(),然后运行起来程序异常终止了,查看log信息:

 E/AndroidRuntime(2206): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

goolgle一下找到了原因: 原来android中相关的view和控件不是线程安全的,我们必须单独做处理。然后就了解了Handler。可以在子线程中通过Handler发送一个Message给主线程,然后在主线程进行UI更新


可以大概看成Handler的作用有分发消息,处理消息,发送消息,移除消息

下面看一下Message类


可见Message包括what(message的标识) 、obj 任意对象, arg1 arg2, 而且可以设置Target来指定Handler


当Handler发送一条Message时有一下两种写法:

Message msg = Message.obtain();
msg.what = 200;
msg.obj = obj;
handler.sendMessage(msg);

Message.obtain(handler, 200).sendToTarget();

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 prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation of prepare and loop to create an initial Handler to communicate with the Looper.

  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }


 Handler的作用?
1)在非UI线程更新UI ;

2)发送一个延时消息;

3)当做定时器,每隔一段时间发送一次消息,如进行图片轮播

为什么android设计只能UI线程更新UI?
1) 解决多线程并发的问题
2) 提高界面更新的性能问题
3) 架构设计的简单
Handler 相关的异常

1)E/AndroidRuntime(2206): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

 不能子线程更新UI的异常{解决:在子线程向主线程中的handler发送Message}

2E/AndroidRuntime(2329): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

不能在子线程中new Handlder(),我们需要调用Looper.prepare(); 后new Handler然后 Looper.loop();

我们自己创建的线程中没有Looper对象,这里注意一点,在ActivityThread线I程中会隐士的调用Looper.prepare()方法

在下面我们会看一下Looper.prepare()方法的源码

 Handler、Looper、MessageQueue之间的关系(源码角度分析)?
Handler 的构造方法:
/**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with represent to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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());
            }
        }
        //获取Looper
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue; //获取Looper中的MessageQueue
        mCallback = callback;
        mAsynchronous = async;
    }

</pre>Looper.myLooper();</div><div><pre name="code" class="java"> /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
final MessageQueue mQueue;

而Handler的各种sendMessage方法最终都会调用sendMessageAtTime(Message msg, long uptimeMillis)
 /**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {@link #handleMessage}, in the thread attached
     * to this handler.
     *
     * @param uptimeMillis The absolute time at which the message should be
     *         delivered, using the
     *         {@link android.os.SystemClock#uptimeMillis} time-base.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    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入队到mQueue中
    }
 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,也就是Handler自身


可以看成当我们new Handlder时回从ThreadLocal中get一个Looper对象,而Looper中含有一个消息队列MessageQueue,当我们调用Handler的sendMessageXXX等方法时,会将一个Message对象添加到Looper的MessageQueue中,那么Looper中是如何处理Message的呢
Looper的构造方法: 可以看成这里会new一个MessageQueue对象,然后mThread为当前线程
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Looper. prepare()方法,因为Looper的构造方法是私有,Handler调用mThreadLocal.get()方法来获得Looper对象,而Looper的prepare方法中会new一个Looper放到mThreadLocal中
/** Initialize the current thread as a looper. 初始化一个looper
      * This gives you a chance to create handlers that then reference 该方法提供给用户一个机会去创建handler来
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }



我们查看Looper的Loop方法
 /**
     * 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 //不断获取下一个Message
            if (msg == null) { //当队列为空时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); //这里调用msg.target(也就是handler)的<span style="font-family: Arial, Helvetica, sans-serif;"></span>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();
        }
    }

这里调用msg.target(也就是handler)的dispatchMessage(msg);   我们来看handler的dispatchMessage方法
 /**
     * 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);
        }
    }

可以看到最终会回调执行我们熟悉的 handleMessage(msg);



1).Looper 内部包含一个消息队列 MessageQueue,suoyoudeHandler发送的消息都走向这个消息队列Looper.Looper方法,一个死循环,不断从MessageQueue取消息,有消息就处理,没有就阻塞

2).MessageQueue一个消息队列,可以添加消息,并处理消息
3).Handler   Handler封装了消息的发送(主要包括消息发送的对象,如何处理)内部跟Looper相关联,也就是说在handler的内部可以找到Looper然后可以获得Message,在Handler中发送消息,其实是向MessageQueue队列中发送消息

总结:handler负责发送消息,Looper负责接受Handler发送来的消息,并把消息回传给handler自己,MessageQueue是一个存储消息的容器



结合图片看看这个过程