Handler消息通信機制完全解析篇

本文有借鑒過網(wǎng)絡上優(yōu)秀的文章,加上自己的總結(jié)。

為什么要使用Handler?

為了保證Android的UI操作是線程安全的,Android規(guī)定只允許UI線程修改UI組件。
但在實際開發(fā)中,必然會遇到多個線程并發(fā)操作UI組件的時候,這將導致UI操作的線程不安全。
問題在于,如何同時滿足:

  1. 保證線程安全
  2. 使多個線程并發(fā)操作UI組件
    Handler消息機制可以解決這個問題。

是否熟悉以下相關概念?YES的話本段可略過!

  • 主線程
    定義:程序第一次啟動時,Android會同時啟動一條主線程(MainThread)
    作用:主線程主要負責處理與UI相關的事件,所以主線程又叫UI線程
  • Message
    定義:Handler接收和處理的消息對象,可以理解為封裝了某些數(shù)據(jù)的對象
    使用:后臺線程處理完數(shù)據(jù)后需要更新UI,可發(fā)送一條包含更新信息的Message給UI線程
  • Message Queue
    定義:消息隊列
    作用:用來存放通過Handler發(fā)送的消息,按照先進先出的順序排列
  • Handler
    定義:Handler是Message的主要處理者
    作用:
    1.負責將Message添加到消息隊列中
    2.處理Looper分派過來的Message
  • Looper
    定義:循環(huán)器,不斷的取出MessageQueue中的消息并傳遞給Handler
    作用:循環(huán)取出MessageQueue的Message,將取出的Message交付給相應的Handler
    PS:每個線程只能擁有一個Looper,但一個Looper可以和多個線程的Handler綁定,也就是說多個線程可以往一個Looper所持有的MessageQueue中發(fā)送消息,這給我們提供了線程之間通信的可能。

Handler工作流程

  • 異步通信的準備

1.Looper對象的創(chuàng)建和實例化
Looper.prepare()
Looper.loop()

2.MessageQueue隊列的創(chuàng)建
Looper.prepare()->new Looper()
一個線程只會有一個Looper實例,同時一個Looper實例也只有會創(chuàng)建一個MessageQueue。

3.Handler實例化
Handler是和線程綁定在一起的,初始化Handler的時候一般通過指定Looper對象從而綁定相應線程,即給Handler指定Looper對象相當于綁定到了Looper對象所在的線程中。Handler的消息處理回調(diào)會在那個線程中執(zhí)行。

實例化Handler的方法:
1) 通過Looper.mylooper()得到當前線程的Looper對象,或通過Loop.getMainLooper()獲得當前進程的主線程的Looper對象。
2)不指定Looper對象,這個Handler綁定到創(chuàng)建這個線程的線程上,消息處理回調(diào)也就在在創(chuàng)建線程中執(zhí)行。
當Handler初始化時,可通過構造方法自動關聯(lián)Looper和相應的MessageQueue。

  • 消息發(fā)送
    Handler將消息發(fā)送到消息隊列中

  • 消息循環(huán)
    Looper執(zhí)行Looper.loop()進入消息循環(huán),在循環(huán)過程中不斷從該MessageQueue取出消息,并將取出的消息派發(fā)給創(chuàng)建該消息的Handler...

  • 消息處理
    通過Handler的dispatchMessage(msg)方法,即回調(diào)handleMessage(msg)處理消息。如果時Handler的post方法發(fā)送的消息,則會在對應的run()方法中處理回調(diào)。

源碼分析

Looper.prepare()是在做什么?

     /** 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) {
        //一個線程只能持有一個Looper實例,sThreadLocal保存線程持有的looper對象
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }

        //sThreadLocal是一個ThreadLocal變量,用于在一個線程中存儲變量,這里Looper變量就存放在ThreadLocal里
        sThreadLocal.set(new Looper(quitAllowed));
    }

Looper的構造方法在做什么?

    private Looper(boolean quitAllowed) {
        //創(chuàng)建Looper時,會自動創(chuàng)建一個與之匹配的MessageQueue
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Looper.loop()方法作用是什么?

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        //myLooper()方法是返回sThreadLocal存儲的Looper實例
        final Looper me = myLooper();

        //me==null就會拋出異常,說明looper對象沒有被創(chuàng)建,
        //也就是說loop方法必須在prepare方法之后運行,消息循環(huán)必須要先在線程中創(chuàng)建Looper實例
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }

        //獲取Looper實例中的消息隊列mQueue
        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 (;;) {
            //next()方法用于取出消息隊列中的消息,如果取出的消息為空,則線程阻塞
            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);
            }

            //把消息派發(fā)給msg的target屬性,然后用dispatchMessage方法去處理
            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.recycleUnchecked();
        }
    }

綜上,可以看出Looper的作用是:
1.實例化Looper對象本身(prepare()方法),創(chuàng)建與之對應的MessageQueue(looper()構造方法)
2.loop()方法不斷從MessageQueue中取消息,派發(fā)給Handler,然后調(diào)用相應Handler的dispatchMessage()方法進行消息處理。

那么,Handler是如何和Looper綁定且從MessageQueue中獲取消息執(zhí)行的呢?
來看Handler的構造方法:

    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.myLooper()獲得了當前線程保存的Looper實例
        mLooper = Looper.myLooper();

        //如果沒有l(wèi)ooper實例就會拋出異常,這說明一個沒有創(chuàng)建looper的線程中是無法創(chuàng)建一個Handler對象的;
        //子線程中創(chuàng)建一個Handler時需要創(chuàng)建Looper,且開啟循環(huán)才能使用這個Handler
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }

        //獲取looper實例的MessageQueue,保證handler實例與looper實例的MessageQueue關聯(lián)
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

以上,當Handler構造函數(shù)初始化時,自動關聯(lián)looper和對應的MessageQueue。

Handler向MessageQueue發(fā)送消息的代碼sendMessage執(zhí)行后,是發(fā)生了什么?

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

    //向下調(diào)用
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    //向下調(diào)用
    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);
    }

    //sendMessage最后的最后調(diào)用到了enqueueMessage方法
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        // msg.target = this,也就是把當前handler作為msg的target屬性
        // 在Looper的loop()方法中會取出msg,然后執(zhí)行msg.target.dispatchMessage(msg)去處理消息
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }

        //handler發(fā)出的消息最終會保存到消息隊列中
        return queue.enqueueMessage(msg, uptimeMillis);
    }

Handler的post()和sendMessage()有什么不同?

    public final boolean post(Runnable r) {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    
    private static Message getPostMessage(Runnable r) {
        //使用obtain方法創(chuàng)建一個Message對象,因為Message內(nèi)部維護了一個Message池用于Message復用,避免使用new重新分配內(nèi)存
        Message m = Message.obtain();
        //將創(chuàng)建的Runnable對象作為callback屬性,賦值給message
        m.callback = r;
        //返回一個message對象
        return m;
    }

繼續(xù)向下調(diào)用:

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    //向下調(diào)用
    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);
    }

由上可知,Handler的post()方法和sendmessage()方法一樣,最終都調(diào)用了sendMessageAtTime,然后調(diào)用了enqueueMessage方法,將msg.target賦值為handler,然后將Handler加入到MessageQueue中。

But,在使用post方法時,將創(chuàng)建的Runnable對象作為callback屬性賦值給了message,那么該如何執(zhí)行handler的回調(diào)方法呢?請看如下代碼:

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        //如果msg.callback不為null,則執(zhí)行handleCallback回調(diào),也就是我們的Runnable里的回調(diào)
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    //Runnable的run()方法中執(zhí)行回調(diào)函數(shù)
    private static void handleCallback(Message message) {
        message.callback.run();
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

可以看到dispatchMessage()方法中調(diào)用了handleMessage()方法,但是是一個空方法,在創(chuàng)建Handler時通過復寫handleMessage()方法來實現(xiàn)我們需要的消息處理方式,根據(jù)msg.what標識進行區(qū)分處理。

為什么在UI線程中使用Handler時不需要創(chuàng)建Looper?

當一個Android應用程序啟動時,會創(chuàng)建一個主線程ActivityThread,在ActivityThread中有一個靜態(tài)的main()方法,也是應用程序的入口點。

 public static void main(String[] args) {
        ...
        //  通過prepareMainLooper方法為主線程創(chuàng)建一個looper
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        // 開啟消息循環(huán)
        Looper.loop();
        ...
    }

    /**
     * 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()方法用于創(chuàng)建一個looper對象
        //主線程的消息循環(huán)是不允許退出的
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

舉幾個例子來加強理解

子線程和主線程通信,使用sendMessage()更新UI

/**
 * Created by Kathy on 17-2-15.
 * 子線程與主線程通信
 */

public class MainActivity extends Activity {

    private static final int INT_ONE = 1;

    //在主線程里創(chuàng)建一個mHandler實例
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case INT_ONE:
                    String text = (String) msg.obj;
                    Toast.makeText(MainActivity.this, text,Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return false;
        }
    });


    class ThreadOne extends Thread{
        @Override
        public void run() {
            //創(chuàng)建需要發(fā)送的消息,注意使用的是主線程的mHandler,所以也在主線程的handleMessage()中回調(diào)
            Message msg = Message.obtain();
            msg.what = INT_ONE; //標識消息
            msg.obj = "One"; //存放消息
            mHandler.sendMessage(msg);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //啟動子線程
        new ThreadOne().start();
    }
}

啟動這個Activity,執(zhí)行子線程,在子線程中通過UI線程的mHandler發(fā)送消息,會發(fā)現(xiàn)最終會執(zhí)行到handleMessage()方法,彈出Toast。

使用Handler.post()更新UI

/**
 * Created by Kathy on 17-2-16.
 * 使用Handler.post()通信
 */

public class MainActivityTwo extends Activity {

    private Handler mHandler;

    //使用mHandler.post()方法只需要在run()方法中寫回調(diào)內(nèi)容即可
    class ThreadTwo extends Thread {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivityTwo.this, "Two", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 實例化Handler,無需指定looper,mHandler自動綁定當前線程(UI線程)的Looper和MessageQueue
        mHandler = new Handler();

        new ThreadTwo().start();
    }
}

主線程如何向子線程中發(fā)送消息的呢?

/**
 * Created by Kathy on 17-2-16.
 */

public class MainActivityThree extends Activity {

    private Handler mChildHandlerOne;
    private Handler mChildHandlerTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d("Kathy", "mainLooper = " + getMainLooper());

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                //子線程中實例化mChildHandlerOne
                mChildHandlerOne = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        Log.d("Kathy", "mChildHandlerOne received Message!");

                        // 在此線程中,用mChildHandlerTwo發(fā)送消息
                        // 消息被加入到mChildHandlerTwo的消息隊列中,進而會執(zhí)行到mChildHandlerTwo的回調(diào)方法
                        // 這就完成了子線程向子線程之前發(fā)消息的可能
                        Message msg2 = Message.obtain();
                        msg2.what = 1;
                        mChildHandlerTwo.sendMessage(msg2);
                        return false;
                    }
                });
                Log.d("Kathy", "mChildHandlerOne = " + mChildHandlerOne.getLooper());
                Looper.loop();

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                //子線程中實例化mChildHandlerTwo
                mChildHandlerTwo = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        Log.d("Kathy", "mChildHandlerTwo received Message!");
                        return false;
                    }
                });
                Log.d("Kathy", "mChildHandlerTwo = " + mChildHandlerTwo.getLooper());
                Looper.loop();
            }
        }).start();

        // 點擊按鈕,如果兩個子線程中的handler都被實例化后,在主線程中,用mChildHandlerOne發(fā)送消息
        // 消息會加入到mChildHandlerOne的消息隊列中,進而會執(zhí)行到mChildHandlerOne的回調(diào)方法
        // 這就完成了在主線程中向子線程發(fā)送消息的可能
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mChildHandlerOne && null != mChildHandlerTwo) {
                    Message msg1 = Message.obtain();
                    msg1.what = 1;
                    mChildHandlerOne.sendMessage(msg1);
                }
            }
        });
    }
}

Log輸出如下:

02-17 15:41:14.998 22131-22131/com.demo.kathy.demo D/Kathy: mainLooper = Looper (main, tid 1) {56801a8}
02-17 15:41:15.007 22131-22170/com.demo.kathy.demo D/Kathy: mChildHandlerOne = Looper (Thread-5565, tid 5565) {dba14c1}
02-17 15:41:15.009 22131-22171/com.demo.kathy.demo D/Kathy: mChildHandlerTwo = Looper (Thread-5566, tid 5566) {8d3d466}
02-17 15:41:28.490 22131-22170/com.demo.kathy.demo D/Kathy: mChildHandlerOne received Message!
02-17 15:41:28.490 22131-22171/com.demo.kathy.demo D/Kathy: mChildHandlerTwo received Message!

若有錯誤,請及時指出,感謝閱讀!

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容