1. 程式人生 > >Android訊息機制原始碼解析(Handler)

Android訊息機制原始碼解析(Handler)

Android訊息機制,其實也就是Handler機制,主要用於UI執行緒和子執行緒之間互動。眾所周知,一般情況下,出於安全的考慮,所有與UI控制元件的操作都要放在主執行緒即UI執行緒中,而一些耗時操作應當放在子執行緒中。當在子執行緒中完成耗時操作並要對UI控制元件進行操作時,就要用Handler來控制。另外,Android系統框架內,Activity生命週期的通知等功能也是通過訊息機制來實現的。本篇博文主要是想通過Handler原始碼解析,來加深我自己對Android訊息機制的理解。

一、Handler使用

使用例子:

private Handler handler = new Handler(){//1.Handler初始化,一個匿名內部類
@Override public void handleMessage(Message msg) { super.handleMessage(msg); textView.setText("對UI進行操作"); } }; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.mytv); new
Thread(new Runnable() { @Override public void run() { //模擬耗時操作 SystemClock.sleep(3000); handler.sendMessage(new Message());//2.在子執行緒中sendMessage(); } }).start(); }

1.我們先來看看,Handler初始化。
Handler初始化的同時,也實現了訊息處理方法handleMessage()。檢視Handler原始碼

    final MessageQueue mQueue;
    final Looper mLooper;
    final Callback mCallback;
    /**
     * Default constructor associates this handler with the queue for the
     * current thread.
     *
     * If there isn't one, this handler won't be able to receive messages.
     */
    public Handler() {
        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();//3.核心程式碼。獲取一個Looper
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;//4.核心程式碼。從Looper獲取一個訊息佇列
        mCallback = null;
    }

在原始碼中,Handler定義了一個MessageQueue訊息佇列mQueue和一個Looper物件mLooper,並都進行了初始化,分別對mQueue和mLooper進行了賦值,其中mLooper是通過Looper.myLooper()賦值,mQueues是Looper中的mQueue。通過了解,知Looper.myLooper()是一個靜態方法。讓我們進入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.
  *
  * <pre>
  *  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();
  *      }
  *  }</pre>
  */
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));
    }

    /**
     * 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();
        }
    }

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
       ......
    }

    /**
     * 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();
    }
   ......
}

從Looper原始碼的註釋中,我們知道Looper是一個專門為執行緒提供訊息迴圈的類,通過呼叫prepare()和loop()就可以為執行緒提供一個訊息迴圈機制。執行緒本來是沒有訊息迴圈機制的,想要訊息迴圈機制就必須自己建立。如:

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

在Looper原始碼中,有兩個方法prepare()和prepareMainLooper()對Looper進行了初始化,Looper.myLooper()核心程式碼為sThreadLocal.get(),主要也是從sThreadLocal中取值。兩個初始化方法的原始碼為

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

    /**
     * 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();
        }
    }

從原始碼中知道prepare()建立的Looper為允許退出迴圈的,而prepareMainLooper()方法建立的是不應許退出迴圈的,通過分析,很明顯知道prepare()方法建立的是一般執行緒的Looper,而通過而prepareMainLooper()建立的,就是主執行緒訊息迴圈的Looper。

現在,雖然我們知道了Handler中對MessageQueue佇列和Looper進行了賦值,但是Looper啥時候通過prepareMainLooper()初始化的呢?什麼是開始調loop()開始迴圈的呢?這裡我們先停一下,後面我們會說道。

2.我們再看例子中的註釋方法,在子執行緒中handler.sendMessage(message)

我們繼續看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)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;//1.對Message中的target賦值Handler
            sent = queue.enqueueMessage(msg, uptimeMillis);//2.向迴圈佇列中,加入訊息
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }
....

閱讀Handler原始碼知,傳送訊息的方法還有許多種,sendMessage()是其中一種,如果還想具體瞭解還有哪些,可以下載Handler原始碼看一下,這裡就不一一介紹了。從上面三個方法中我們瞭解到方法sendMessageAtTime()是最後呼叫的,這個方法主要是,對Message的target賦值為傳送主體Handler,並把Message加入訊息佇列MessageQueue中,等待訊息佇列迴圈處理。

Handler傳送主體為Message,Message是啥呢?Message主要就是對一些資料做封裝處理,其中有int變數what,arg1,arg2,Object變數obj等,具體可以檢視Message原始碼,這裡就不詳細說了。

二、Looper的建立及迴圈機制

上面說到,Looper的建立有兩種方式prepare()和prepareMainLooper(),其中prepare建立的為一般子執行緒Looper,可以取消迴圈;而prepareMainLooper()建立的為主執行緒的Looper,不可以取消迴圈。到底而prepareMainLooper建立的是不是主執行緒迴圈呢?讓我們繼續分析

1.主執行緒Looper建立

主執行緒即UI執行緒,說到UI執行緒,我們知道應用程式一啟動,主(UI)執行緒就開始啟動,而執行緒的建立必須要在程序的基礎上。通過對Android應用程式啟動的分析,我們知道,應用程式啟動,首先會通過Zygote複製自身fork出一個程序,然後再由程序建立一個主執行緒,主執行緒的建立和ActivityThread息息相關,通過分析,知ActivityThread的main方法就是應用程式啟動的入口。具體可以參考:Android應用程式入口原始碼解析

讓我們來看一下ActivityThread類的main方法:

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

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();//1.主執行緒Looper建立
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler();
        }

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        AsyncTask.init();

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();//2.主執行緒Looper迴圈

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

從原始碼知道,正如我們想的那樣prepareMainLooper()建立的Looper就是主執行緒的Looper。

2.Looper的訊息迴圈

從上面ActivityThread的main方法中,我們發現Looper.loop()訊息迴圈方法。Looper是怎麼迴圈的,這裡讓我們來看一下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 (;;) {//for迴圈
            Message msg = queue.next(); //從訊息佇列中取值
            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();
        }
    }

從loop()原始碼中我們知道,建立了一個for迴圈從訊息佇列中取資料,然後通過msg.target.dispatchMessage(msg)分發訊息,從前面我們知道target就是handler,這裡我們再看一下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);
        }
    }

在這裡我們就看到,Handler最後會呼叫handleMessage()方法,只要message中callback為空,就是呼叫handleMessage(),從而實現訊息的處理。

到這裡,我們Android Handler訊息分發機制解析就分解完了。但這裡需要注意一下的是,在loop迴圈中,如果訊息為空就會跳出迴圈,而我們的主執行緒Looper迴圈應該是死迴圈才對。針對這個問題,我們繼續深入原始碼看一下,前面說prepare()和prepareMainLooper()是兩種建立Looper的方式,兩者的區別是一個是可取消迴圈的,一個是不可以取消迴圈的,這裡讓我們再來看看一下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));
    }

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

通過檢視原始碼發現,是否可以取消訊息迴圈,主要控制是MessageQueue裡面,這裡我們可以知道,主執行緒的訊息迴圈控制應該就在 queue.next()方法裡,好了,讓我們來看MessageQueue的next方法

  final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);//1.核心程式碼

            synchronized (this) {
                if (mQuiting) {
                    return null;
                }

            .......省略程式碼,獲取訊息佇列中的Message      

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

在next()方法中,有一個原生方法nativePollOnce(),它的作用是幹啥的呢?是不是就是控制主執行緒迴圈的呢?通過進一步閱讀C++原始碼,我們知道這裡是利用Linux系統中epoll_wait方法來進行阻塞,形成一個等待狀態,也就是說,當訊息佇列中訊息為空時,nativePollOnce()方法不會返回,會進行阻塞,形成一個等待狀態,等有新訊息進入訊息佇列,才會返回,從而獲取訊息。這裡我們也來看一下訊息佇列的插入方法

  final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }
            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }
        }
        if (needWake) {
            nativeWake(mPtr);//核心程式碼
        }
        return true;
    }

在訊息佇列中加入訊息之後,會呼叫一個原生方法 nativeWake(),這個原生的C++的方法,也就是通知nativePollOnce()返回的方法,通過方法nativeWake和nativePollOnce的一唱一和,從而實現主執行緒的訊息佇列的無限迴圈。

好了,分析就到這裡了。

三、總結

Android訊息分發機制,也就是Handler處理訊息機制。流程如下:

  • 1.應用程式在啟動的時候,通過Zygote複製自身fork出應用程式的程序,然後該程序又以ActivityThread建立主執行緒。
  • 2.主執行緒啟動時,在ActivityThread的main方法中初始化了Looper和執行訊息佇列的迴圈。
  • 3.使用過程中,Handler初始化,獲取了主執行緒的Looper和訊息佇列MessageQueue,並實現訊息處理方法handlerMessage
  • 4.Handler通過sendMessage方法將訊息插入訊息佇列
  • 5.通過Looper訊息佇列的迴圈,從而執行處理方法,實現了UI執行緒和子執行緒之間的互動。

注:原始碼採用android-4.1.1_r1版本,建議下載原始碼然後自己走一遍流程,這樣更能加深理解。

四、相關及參考文件