Android 源碼(6) --- 異步消息機制Handler拱撵、Looper辉川、MessageQueue

Handler、Looper拴测、MessageQueue 初始化

  • 1.在 UI 線程創(chuàng)建 Handler乓旗,通常直接new Handler;
private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            }
        }
UI Thread 初始Handler化時 對Looper進行初始化過程, main()是在 UI Thread 啟動時調用

```
 public static void main(String[] args) {
        SamplingProfilerIntegration.start();
        
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        EventLogger.setReporter(new EventLoggingReporter());

        Security.addProvider(new AndroidKeyStoreProvider());

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

```
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
public static void prepare() {
        prepare(f);
    }
    
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));
_    }
```
以上是UI Thread 初始化new Handler 調用過程
  • 2.接下來看一下 Other Thread 初始化調用屿愚。

    Looper.prepare();
    private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                }
            }
    

    查看下Looper.prepare();

    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));
    _    }
    
    
  • 3.其他用法: 在其他地方需要用到Handler,并且需要刷新UI時,不通過Looper.prepare();調用务荆,通過Looper.getMainLooper()也可以妆距;
` Handler mHandler = new Handler(Looper.getMainLooper());

class Looper{
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }
} `
  • 4.MessageQueue 初始化

     private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
        ```
    Looper 在初始化時創(chuàng)建一個關聯(lián)MessageQueue,一個線程中對應一個Looper & MessageQueue 
        
    
  • Handler 初始化

    // 常用構造
    public Handler(Callback callback) {
        this(callback, 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;
    }
        ```
    
    
    從這里我們基本可以看到Handler 初始化時函匕,關聯(lián)了線程唯一的Looper & MessageQueue娱据。
    
    
    
  • UI Thread 和 其他 Thread 初始完Looper和MessageQueue后,會調用Looper.loop(),來輪詢分發(fā)消息盅惜。

  • 5.梳理一下調用關系吸耿,來張流程圖理解一下;

    • UI Thread:
      ActivityThread.main() -->Looper.prepareMainLooper() --> prepare(false) --> new Looper(quitAllowed) --> new MessageQueue(quitAllowed)

    • Other Thread:
      prepare() --> prepare(true) --> new Looper(quitAllowed) --> new MessageQueue(quitAllowed)

Handler-Looper-MessageQueue流程圖
Handler-Looper-MessageQueue流程圖

異步消息

  • 1.調用,存儲消息
    mHandler.sendMessage(new Message()); mHandler.post(); mHandler.postDelay();

    追蹤一下不難發(fā)現(xiàn)酷窥,最后都走的一個地方

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
        
這樣看msg.target = this;msg.target就是Handler自己咽安,而MessageQueue就是Looper中關聯(lián)的對象,而enqueueMessage()中是對message保存蓬推,進行Message.next()按時間排序妆棒。
  • 2.消費
    Looper.loop()是對MessageQueue的消費
     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();
        }
    }
   

看到loop()中,添加了一個死循環(huán)沸伏,不斷去輪訓MessageQueue中的隊列是否為null糕珊,返回或者取出來繼續(xù)執(zhí)行 msg.target.dispatchMessage(msg);在最開始我們看到msg.target就是Handler本身

    public static Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 101) {
                    Log.i(TAG, "接收到handler消息...");
                }
            }
        };
        

而handleMessage就是我們重寫的回調方法。

  • 3.一張圖梳理一下流程


    流程圖
    流程圖
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末毅糟,一起剝皮案震驚了整個濱河市红选,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌姆另,老刑警劉巖喇肋,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件坟乾,死亡現(xiàn)場離奇詭異,居然都是意外死亡蝶防,警方通過查閱死者的電腦和手機甚侣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來间学,“玉大人殷费,你說我怎么就攤上這事〉秃” “怎么了详羡?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嘿悬。 經(jīng)常有香客問我殷绍,道長,這世上最難降的妖魔是什么鹊漠? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮茶行,結果婚禮上躯概,老公的妹妹穿的比我還像新娘。我一直安慰自己畔师,他們只是感情好娶靡,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著看锉,像睡著了一般姿锭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上伯铣,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天呻此,我揣著相機與錄音,去河邊找鬼腔寡。 笑死焚鲜,一個胖子當著我的面吹牛,可吹牛的內容都是我干的放前。 我是一名探鬼主播忿磅,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼凭语!你這毒婦竟也來了葱她?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤似扔,失蹤者是張志新(化名)和其女友劉穎吨些,沒想到半個月后搓谆,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡锤灿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年挽拔,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片但校。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡螃诅,死狀恐怖,靈堂內的尸體忽然破棺而出状囱,到底是詐尸還是另有隱情术裸,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布亭枷,位于F島的核電站袭艺,受9級特大地震影響,放射性物質發(fā)生泄漏叨粘。R本人自食惡果不足惜猾编,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望升敲。 院中可真熱鬧答倡,春花似錦、人聲如沸驴党。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽港庄。三九已至倔既,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鹏氧,已是汗流浹背渤涌。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留把还,地道東北人歼捏。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像笨篷,于是被迫代替她去往敵國和親瞳秽。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內容