Android中的Handler消息处理机制

本文深入解析Android中的Handler机制,从Looper、MessageQueue的初始化到消息的发送与接收流程,全面阐述Handler的工作原理。

在几天在学习中用到了android中的Handler消息处理机制,但是对它的原理不太清楚,自己一边学习一边看源代码整理了下Handler的消息处理机制。

首先根据官方给的例子来说明调用关系,在一个线程中创建Handler对象:

  *  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();
  *      }
  *  }
1、可以看到首先会调用 Looper.prepare(); 方法,然后在创建Handler对象,那么这个Looper又是什么呢,这个要到源码中去看了。

public class Looper {
    private static final String TAG = "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;
    final Thread mThread;
    volatile boolean mRun;

    private Printer mLogging;

     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * 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的prepare()方法中先是 new 了一个Looper对象,Looper的构造方法在这

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

然后sThreadLocal.set()把这个new 出来的 Looper对象放入到 ThreadLocal中,这就是整个Looper.prepare()方法做的事情

2、在例子中 new 了一个Handler对象,那么就从源码中找出这个Handler对象是怎么new出来的

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

在代码中new的时候先调用的Handler的默认构造方法,然后在这个默认构造方法中调用了上面带两个参数的构造方法,在这个方法中,mLooper = 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 Looper myLooper() {
        return sThreadLocal.get();
    }

清楚的看出通过sThreadLocal的get()方法得到了之前Looper.prepare()方法放入的Looper对象,所以Handler对象中的Looper对象,就是之前线程中的Looper对象。

接着上面的代码, mQueue = mLooper.mQueue; 这行代码得到Looper对象中的MessageQueue对象,那么这个MessageQueue对象又是什么时候创建的呢,往前看,发现是在Looper的prepare()方法中创建Looper对象的时候就创建了,所以也就是说 一个Looper对象对应着一个MessageQueue对象,而一个线程中只有一个Looper对象。


3、经过上面,Handler对象就创建完毕了,然后 调用Looper.loop()方法,这个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
            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.recycle();
        }
    }

可以看到首先得到MessageQueue对象,然后是一个for死循环,在这个循环中,先是 Message msg = queue.next(); 这行代码意思是什么?

这个next方法其实就是把MessageQueue队列中的Message方法拿出来,然后msg.target.dispatchMessage(msg); msg.target就是代表了这个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);
        }
    }

可以看到是调用了hanleMessage(msg)方法,这个就是我们在之前 创建Handler对象时重写的那个handlerMessage方法,然后我们就得到了发送出来的Message对象,自己去处理消息了。


4、以上是一个线程中Handler创建过程和接收到Message过程,那么发送消息的过程呢,我们知道Handler最多用于在不同线程中,往另一个线程里发送消息,然后在那个线程中接收到handler发送到的消息,对消息进行处理。那么发送过程是怎么实现的

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

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

上面是sendMessage时候调用的一系列方法,看倒数第二个方法,可以看看到是先得到MessageQueue对象,然后最后一个方法中,调用queue.enqueueMessage()方法,在这个方法中把Message消息放入到MessageQueue消息队列中,在之前的Looper.loop()方法不断的从消息队列中取出Message对象,然后去处理消息。


经过上面的分析可以很清楚的看到了整个Handler消息机制的原理了,总结下,就是一个线程中有一个Looper对象,这个Looper对象有一个MessageQueue消息队列,别的线程中通过拥有handler对象实例来调用sendMessage()方法,在这个方法中是用的Looper对象的MessageQueue消息队列来把Message放入到队列中,然后在第一个线程中,Looper对象的loop()方法把消息队列中的Message消息取出,然后交给Handler对象的重写的handleMessage()方法来处理得到的消息。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值