深入了解Looper、Handler、Message之間關系

前言及簡介

前些天我們整個項目組趁著小假期,驅車去了江門市的臺山猛虎峽玩了兩個多鐘左右極限勇士全程漂流,感覺真得不錯,天氣熱就應該多多玩水,多親近一下大自然,不要整天埋頭工作。寫文章主要是讓朋友們一起相互分享學習,共同進步。
好了,言歸正題,今天我們要講的主題是關于Android中的異步消息處理機制的內容。有一點Android基礎的朋友們都知道,在Android中,主線程(也就是UI線程)是不安全的,當在主線程處理消息過長時,非常容易發生ANR(Application Not Responding)現象,這樣對于用戶體驗是非常不好的;其次,如果我們在子線程中嘗試進行UI的操作,程序就可能還會直接崩潰。我相信,對于大多剛入門的朋友,在日常工作當中會經常遇到這個問題,而解決的方法大多已經通過google已了解清楚,也就是在子線程中創建一個消息Message對象,然后利用在主線程中創建的Handler對象進行發送,之后我們可以在這個Handler對象的handlerMessage()方法中獲取剛剛發送的Message對象,取出里面所存儲的值,就可以在這里進行UI的操作。這種方法就稱為異步消息處理線程。
總的來說,異步消息處理線程,說得比較通俗一點就是,當我們啟動此方法后,會進入到一個無限的循環當中,每循環一次,我們就其對應的內部消息隊列(Message Queue)中取出一個消息(Message),然后回調好相應的消息處理函數,當執行完一個消息后則繼續循環,若當消息隊列中消息為空,則線程會被阻塞等待,直到有消息進入時再被喚醒。
好吧,說了那么多,現在,就讓我們來看一下這種處理機制的廬山真面目吧。

分析Handler

首先我們來分析分析一下Handler的用法,我們知道,要創建一個Handler對象非常的簡單明了,直接進行new一個對象即可,但是你有沒有想過,這里會隱藏著什么注意點呢。現在可以試著寫一下下面的一小段代碼,然后自己運行看看:

public class MainActivity extends ActionBarActivity {

    private Handler mHandler0;

    private Handler mHandler1;

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

        mHandler0 = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler1 = new Handler();
            }
        }).start();
    }

這一小段程序代碼主要創建了兩個Handler對象,其中,一個在主線程中創建,而另外一個則在子線程中創建,現在運行一下程序,則你會發現,在子線程創建的Handler對象竟然會導致程序直接崩潰,提示的錯誤竟然是Can't create handler inside thread that has not called Looper.prepare()

于是我們按照logcat中所說,在子線程中加入Looper.prepare(),即代碼如下:

new Thread(new Runnable(){
    @override
    public void run(){
        Looper.prepare();
        mHandler1 = new Handler()l
    }
}).start();

再次運行一下程序,發現程序不會再崩潰了,可是,單單只加這句Looper.prepare()是否就能解決問題了。我們探討問題,就要知其然,才能了解得更多。我們還是先分析一下源碼吧,看看為什么在子線程中沒有加Looper.prepare()就會出現崩潰,而主線程中為什么不用加這句代碼?我們看下Handler()構造函數:

public Handler() {
    this(null, false);
}

構造函數直接調用this(null, false),于是接著看其調用的函數,

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

不難看出,源碼中調用了mLooper = Looper.myLooper()方法獲取一個Looper對象,若此時Looper對象為null,則會直接拋出一個“Can't create handler inside thread that has not called Looper.prepare()”異常,那什么時候造成mLooper是為空呢?那就接著分析Looper.myLooper()

   public static Looper myLooper() {
        return sThreadLocal.get();
   }

這個方法在sThreadLocal變量中直接取出Looper對象,若sThreadLocal變量中存在Looper對象,則直接返回,若不存在,則直接返回null,而sThreadLocal變量是什么呢?

static final ThreadLocat<Looper> sThreadLocal = new ThreadLocal<Looper>();

它是本地線程變量,存放在Looper對象,由這也可看出,每個線程只有存有一個Looper對象,可是,是在哪里給sThreadLocal設置Looper的呢,通過前面的試驗,我們不難猜到,應該是在Looper.prepare()方法中,現在來看看它的源碼:

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()方法中給sThreadLocal變量設置Looper對象,這樣也就理解了為什么要先調用Looper.prepare()方法,才能創建Handler對象,才不會導致崩潰。但是,仔細想想,為什么主線程就不用調用呢?不要急,我們接著分析一下主線程,我們查看一下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);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    Security.addProvider(new AndroidKeyStoreProvider());

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

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

    Looper.prepareMainLooper();

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

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

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

    Looper.loop();

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

代碼中調用了Looper.prepareMainLooper()方法,而這個方法又會繼續調用了Looper.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();
    }
}

分析到這里已經真相大白,主線程中google工程師已經自動幫我們創建了一個Looper對象了,因而我們不再需要手動再調用Looper.prepare()再創建,而子線程中,因為沒有自動幫我們創建Looper對象,因此需要我們手動添加,調用方法是Looper.prepare(),這樣,我們才能正確地創建Handler對象。

發送消息

當我們正確的創建Handler對象后,接下來我們來了解一下怎么發送消息,有一點基礎的朋友肯定對這個方法已經了如指掌了。具體是先創建出一個Message對象,然后可以利用一些方法,如setData()或者使用arg參數等方式來存放數據于消息中,再借助Handler對象將消息發送出去就可以了。

    new Thread(new Runnable() {
        @Override
        public void run() {
            Message msg = Message.obtain();
            msg.arg1 = 1;
            msg.arg2 = 2;
            Bundle bundle = new Bundle();
            bundle.putChar("key", 'v');
            bundle.putString("key","value");
            msg.setData(bundle);
            mHandler0.sendMessage(msg);
        }
    }).start();

通過Message對象進行傳遞消息,在消息中添加各種數據,之后再消息通過mHandler0進行傳遞,之后我們再利用Handler中的handleMessage()方法將此時傳遞的Message進行捕獲出來,再分析得到存儲在msg中的數據。但是,這個流程到底是怎么樣的呢?具體我們還是來分析一下源碼。首先分析一下發送方法sendMessage():

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

通過調用sendMessageDelayed(msg, 0)方法

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

再能過調用sendMessageDelayed(Message msg, long delayMillis),方法中第一個參數是指發送的消息msg,第二個參數是指延遲多少毫秒發送,我們著重看一下此方法:

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

由這里可以分析得出,原來消息Message對象是建立一個消息隊列MessageQueue,這個對象MessageQueue由mQueue賦值,而由源碼分析得出mQueue = mLooper.mQueue,而mLooper則是Looper對象,我們由上面已經知道,每個線程只有一個Looper,因此,一個Looper也就對應了一個MessageQueue對象,之后調用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);
}

方法通過調用MessageQueue對enqueueMessage(Message msg, long uptimeMills)方法:

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

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w("MessageQueue", e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        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;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

首先要知道,源碼中用mMessages代表當前等待處理的消息,MessageQueue也沒有使用一個集合保存所有的消息。觀察中間的代碼部分,隊列中根據時間when來時間排序,這個時間也就是我們傳進來延遲的時間uptimeMills參數,之后再根據時間的順序調用msg.next,從而指定下一個將要處理的消息是什么。如果只是通過sendMessageAtFrontOfQueue()方法來發送消息

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    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, 0);
}

它也是直接調用enqueueMessage()進行入隊,但沒有延遲時間,此時會將傳遞的此消息直接添加到隊頭處,現在入隊操作已經了解得差不多了,接下來應該來了解一下出隊操作,那么出隊在哪里進行的呢,不要忘記MessageQueue對象是在Looper中賦值,因此我們可以在Looper類中找,來看一看Looper.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.recycleUnchecked();
    }
}

代碼比較多,我們只挑重要的分析一下,我們可以看到下面的代碼用for(;;)進入了一個死循環,之后不斷的從MessageQueue對象queue中取出消息msg,而我們不難知道,此時的next()就是進行隊列的出隊方法,next()方法代碼有點長,有興趣的話可以自行翻閱查看,主要邏輯是判斷當前的MessageQueue是否存在待處理的mMessages消息,如果有,則將這個消息出隊,然后讓下一個消息成為mMessages,否則就進入一個阻塞狀態,一直等到有新的消息入隊喚醒。回看loop()方法,可以發現當執行next()方法后會執行msg.target.dispatchMessage(msg)方法,而不難看出,此時msg.target就是Handler對象,繼續看一下dispatchMessage()方法:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

先進行判斷mCallback是否為空,若不為空則調用mCallback的handleMessage()方法,否則直接調用handleMessage()方法,并將消息作為參數傳出去。這樣我們就完全一目了然,為什么我們要使用handleMessage()來捕獲我們之前傳遞過去的信息。
現在我們根據上面的理解,不難寫出異步消息處理機制的線程了。

class myThread extends Thread{
    public Handler myHandler;

    @Override
    public void run() {
        Looper.prepare();
        myHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //處理消息
            }
        };
       Looper.loop();
    }
}

當然除了發送消息外,還有以下幾個方法可以在子線程中進行UI操作:

  • View的post()方法
  • Handler的post()方法
  • Activity的runOnUiThread()方法

其實這幾個方法的本質都是一樣的,只要我們勤于查看這幾個方法的源碼,不難看出最后調用的也是Handler機制,也是借用了異步消息處理機制來實現的。

總結

通過上面對異步消息處理線程的講解,我們不難真正地理解到了Handler、Looper以及Message之間的關系,概括性來說,Looper負責的是創建一個MessageQueue對象,然后進入到一個無限循環體中不斷取出消息,而這些消息都是由一個或者多個Handler進行創建處理。
接下來朋友們想要了解哪方面的東西或者有什么好的想法,可以在下面留言交流,我會盡自己的能力選擇分享給朋友們,當然,如果有什么分享錯誤或者不懂的地方,可以相互交流,期待每個朋友在我的博文中都能學到東西,如果覺得好的話,麻煩各位兄弟關注一下,謝謝!!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容