Android線程的Looper相關(guān)知識(shí)

Android線程的Looper敦锌,Handler相關(guān)知識(shí)


Android中的Looper類馒疹,是用來封裝消息循環(huán)和消息隊(duì)列的一個(gè)類,用于在android線程中進(jìn)行消息處理乙墙。Handler其實(shí)可以看做是一個(gè)工具類颖变,用來向消息隊(duì)列中插入消息的生均。

Android官方文檔中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.

Looper實(shí)現(xiàn)原理

1. Looper可以理解為一個(gè)類似輪詢器
2. Looper在創(chuàng)建的時(shí)候,會(huì)自動(dòng)創(chuàng)建一個(gè)MessageQueue(消息隊(duì)列)腥刹。
3. 將內(nèi)部線程對(duì)象指向自動(dòng)創(chuàng)建的線程马胧。
4. 然后當(dāng)Looper開啟的時(shí)候,去不斷遍歷“詢問”消息隊(duì)列衔峰,如果沒有消息佩脊,隊(duì)列為空,那么就繼續(xù)輪詢
垫卤。如果有消息進(jìn)入隊(duì)列威彰,則對(duì)消息進(jìn)行處理,回調(diào)handler的handlemessage方法進(jìn)行處理

Looper創(chuàng)建的流程

  1. Looper類用來為一個(gè)線程開啟一個(gè)消息循環(huán)穴肘。 默認(rèn)情況下android中新誕生的線程是沒有開啟消息循環(huán)的歇盼。(主線程除外,主線程系統(tǒng)會(huì)自動(dòng)為其創(chuàng)建Looper對(duì)象评抚,開啟消息循環(huán)豹缀。) Looper對(duì)象通過MessageQueue來存放消息和事件。一個(gè)線程只能有一個(gè)Looper盈咳,對(duì)應(yīng)一個(gè)MessageQueue耿眉。

  2. 通常是通過Handler對(duì)象來與Looper進(jìn)行交互的。Handler可看做是Looper的一個(gè)接口鱼响,用來向指定的Looper發(fā)送消息及定義處理方法鸣剪。 默認(rèn)情況下Handler會(huì)與其被定義時(shí)所在線程的Looper綁定,比如丈积,Handler在主線程中定義筐骇,那么它是與主線程的Looper綁定。 mainHandler = new Handler() 等價(jià)于new Handler(Looper.myLooper()). Looper.myLooper():獲取當(dāng)前進(jìn)程的looper對(duì)象江滨,類似的 Looper.getMainLooper() 用于獲取主線程的Looper對(duì)象铛纬。

  3. 在非主線程中直接new Handler() 會(huì)報(bào)如下的錯(cuò)誤:

    E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught 
    exception E/AndroidRuntime( 6173): Java.lang.RuntimeException: Can't create handler inside 
    thread that has not called Looper.prepare()
    

    原因是非主線程中默認(rèn)沒有創(chuàng)建Looper對(duì)象,需要先調(diào)用Looper.prepare()啟用Looper唬滑。
    Looper.prepare()相關(guān)代碼:

    /**
      * 初始化Looper告唆,調(diào)用loop()方法開始循環(huán),調(diào)用quit()退出
      * 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) {//一個(gè)線程只能有一個(gè)Looper
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //保存Looper
        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()}
     * 初始化主線程的Looper晶密,不要調(diào)用擒悬。因?yàn)殚_啟主線程的時(shí)候系統(tǒng)已經(jīng)默認(rèn)開啟Looper了再次調(diào)用會(huì)報(bào)異常
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    
    //構(gòu)造函數(shù)
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//創(chuàng)建消息隊(duì)列
        mThread = Thread.currentThread();//綁定當(dāng)前線程
    }
    
  4. Looper.loop()讓Looper開始工作,從消息隊(duì)列里取消息稻艰,處理消息懂牧。

    注意:寫在Looper.loop()之后的代碼不會(huì)被執(zhí)行,這個(gè)函數(shù)內(nèi)部應(yīng)該是一個(gè)循環(huán)尊勿,當(dāng)調(diào)用mHandler.getLooper().quit()后僧凤,loop才會(huì)中止畜侦,其后的代碼才能得以運(yùn)行。
    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.
       //確保此線程的標(biāo)識(shí)是本地進(jìn)程的標(biāo)識(shí)躯保,并跟蹤該標(biāo)識(shí)標(biāo)識(shí)實(shí)際上是什么.旋膳。
       Binder.clearCallingIdentity();
       final long ident = Binder.clearCallingIdentity();
       //開始一個(gè)死循環(huán)
       for (;;) {
           // 從消息隊(duì)列中獲取新的消息,當(dāng)沒有新消息的時(shí)候會(huì)在queue.next()方法中進(jìn)行循環(huán)遍歷
           //直到有新的消息或者調(diào)用Looper.quit()
           Message msg = queue.next(); 
           if (msg == null) {//如果返回的消息為空就表示已經(jīng)調(diào)用MessageQueue.quit();并且已經(jīng)MessageQueue.dispose()
               // No message indicates that the message queue is quitting.
               //Return here if the message loop has already quit and been disposed.
               return;
           }
           //msg.target 是Handler對(duì)象吻氧,這里進(jìn)行消息的分發(fā)
           msg.target.dispatchMessage(msg);
    
           // 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);
           }
           //Message對(duì)象回收
           msg.recycleUnchecked();
       }
    }
    

    Looper.quit()源碼

    
    /**
    * Quits the looper.退出(會(huì)有消息沒有處理完畢就退出)
    * <p>
    * Causes the {@link #loop} method to terminate without processing any
    * more messages in the message queue.
    * </p><p>
    * Any attempt to post messages to the queue after the looper is asked to quit will fail.
    * For example, the {@link Handler#sendMessage(Message)} method will return false.
    * </p><p class="note">
    * Using this method may be unsafe because some messages may not be delivered
    * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
    * that all pending work is completed in an orderly manner.
    * </p>
    *
    * @see #quitSafely
    */
    public void quit() {
       mQueue.quit(false);
    }
    
    /**
    * Quits the looper safely.安全退出(消息處理完畢退出)
    * <p>
    * Causes the {@link #loop} method to terminate as soon as all remaining messages
    * in the message queue that are already due to be delivered have been handled.
    * However pending delayed messages with due times in the future will not be
    * delivered before the loop terminates.
    * </p><p>
    * Any attempt to post messages to the queue after the looper is asked to quit will fail.
    * For example, the {@link Handler#sendMessage(Message)} method will return false.
    * </p>
    */
    public void quitSafely() {
       mQueue.quit(true);
    }
    
  5. 基于以上知識(shí)溺忧,可實(shí)現(xiàn)主線程給子線程(非主線程)發(fā)送消息咏连。把下面例子中的mHandler聲明成類成員盯孙,在主線程通過mHandler發(fā)送消息即可。

    class LooperThread extends Thread  {  
            public Handler mHandler;  
            public void run()   {  
                Looper.prepare();  
                mHandler = new Handler()   {  
                    public void handleMessage(Message msg)   {  
                        // process incoming messages here  
                    }  
                };  
                
                //這里可以做兩個(gè)修改UI的操作
                //1祟滴,Toast可在這里顯示
                //2振惰,Dialog對(duì)話框可以顯示
                //3,Snackbar可在非UI線程中調(diào)用顯示垄懂,不需要Looper.perpare().因?yàn)樗腍ander調(diào)用的主線程Looper
                Looper.loop();  
                //在調(diào)用looper.quit()之前是不會(huì)被調(diào)用的
            }
        }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末骑晶,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子草慧,更是在濱河造成了極大的恐慌桶蛔,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件漫谷,死亡現(xiàn)場(chǎng)離奇詭異仔雷,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)舔示,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門碟婆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人惕稻,你說我怎么就攤上這事竖共。” “怎么了俺祠?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵公给,是天一觀的道長。 經(jīng)常有香客問我蜘渣,道長淌铐,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任宋梧,我火速辦了婚禮匣沼,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘捂龄。我一直安慰自己释涛,他們只是感情好加叁,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著唇撬,像睡著了一般它匕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上窖认,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天豫柬,我揣著相機(jī)與錄音,去河邊找鬼扑浸。 笑死烧给,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的喝噪。 我是一名探鬼主播础嫡,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼酝惧!你這毒婦竟也來了榴鼎?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤晚唇,失蹤者是張志新(化名)和其女友劉穎巫财,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哩陕,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡平项,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了萌踱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片葵礼。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖并鸵,靈堂內(nèi)的尸體忽然破棺而出鸳粉,到底是詐尸還是另有隱情,我是刑警寧澤园担,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布届谈,位于F島的核電站,受9級(jí)特大地震影響弯汰,放射性物質(zhì)發(fā)生泄漏艰山。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一咏闪、第九天 我趴在偏房一處隱蔽的房頂上張望曙搬。 院中可真熱鬧,春花似錦、人聲如沸纵装。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽橡娄。三九已至诗箍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間挽唉,已是汗流浹背滤祖。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留瓶籽,地道東北人匠童。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像棘劣,于是被迫代替她去往敵國和親俏让。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容