Android的消息處理機制(從源碼分析)

學習android的一大樂趣是可以通過源碼學習google大牛們的設計思想。android源碼中包含了大量的設計模式,除此以外,android sdk還精心為我們設計了各種helper類,對于和我一樣渴望水平得到進階的人來說,都太值得一讀了。

android的消息處理有三個核心類:Looper,Handler和Message。其實還有一個Message Queue(消息隊列,以下均稱為MQ),但是MQ被封裝到Looper里面了,開發中不會直接與MQ打交道,因此不作為核心類。


1. 線程的魔法師 Looper

Looper的字面意思是“循環者”,它被設計用來使一個普通線程變成Looper線程(我的英文名就是取自這里,2333)。所謂Looper線程就是循環工作的線程。在程序開發中(尤其是GUI開發中),我們經常會需要一個線程不斷循環,一旦有新任務則執行,執行完繼續等待下一個任務,這就是Looper線程。使用Looper類創建Looper線程很簡單:

public class LooperThread extends Thread {
    @Override
    public void run() {
        // 將當前線程初始化為Looper線程
        Looper.prepare();
        
        // ...其他處理,如實例化handler
        
        // 開始循環處理消息隊列
        Looper.loop();
    }
}

通過上面兩行核心代碼,你的線程就升級為Looper線程了?。?!夠很神奇吧?咱們來看看這兩行代碼各自做了什么。

Looper.prepare()

線程與looper

通過上圖可以看到,現在你的線程中有一個Looper對象,它的內部維護了一個消息隊列MQ。注意,一個Thread只能有一個Looper對象,為什么呢?咱們來看源碼。

public class Looper {
    // 每個線程中的Looper對象其實是一個ThreadLocal,即線程本地存儲(TLS)對象
    private static final ThreadLocal sThreadLocal = new ThreadLocal();
    // Looper內的消息隊列
    final MessageQueue mQueue;
    // 當前線程
    Thread mThread;
    // 。。。其他屬性

    // 每個Looper對象中有它的消息隊列,和它所屬的線程
    private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
    }

    // 我們調用該方法會在調用線程的TLS中創建Looper對象
    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            // 試圖在有Looper的線程中再次創建Looper將拋出異常
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }
    // 其他方法
}

通過源碼,prepare()背后的工作方式一目了然,其核心就是將looper對象定義為ThreadLocal。如果你還不清楚什么是ThreadLocal,請參考 徹底理解ThreadLocal

Looper.loop()

looper.loop

調用loop方法后,Looper線程就開始真正工作了,它不斷從自己的MQ中取出隊頭的消息(也叫任務)執行。其源碼分析如下:

    public static void loop() {
        final Looper me = myLooper();//取得當前線程looper
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//取得當前線程looper中的MQ

           //沒看懂,但不影響理解 ,請自行體會官方注釋
         // 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(); //取出消息
            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);
            }
            // 非常重要!將真正的處理工作交給message的target,即后面要講的handler
            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();
        }
    }

除了prepare()和loop()方法,Looper類還提供了一些有用的方法,比如
Looper.myLooper()得到當前線程looper對象:

 public static final Looper myLooper() {
           // 在任意線程調用 Looper.myLooper()返回的都是那個線程的looper
          return (Looper)sThreadLocal.get();
}

getThread()得到looper對象所屬線程:

 public Thread getThread() {
         return mThread;
 }

除了prepare()和loop()方法,Looper類還提供了一些有用的方法,比如
Looper.myLooper()得到當前線程looper對象:

 public static final Looper myLooper() {
           // 在任意線程調用 Looper.myLooper()返回的都是那個線程的looper
          return (Looper)sThreadLocal.get();
}

getThread()得到looper對象所屬線程:

 public Thread getThread() {
         return mThread;
 }

quit()方法結束looper循環:

public void quit() {
             // 創建一個空的message,它的target為NULL,表示結束循環消息 
            Message msg = Message.obtain();// 發出消息 
            mQueue.enqueueMessage(msg, 0);
}

到此為止,你應該對Looper有了基本的了解,總結幾點:

  1. 每個線程有且最多只能有一個Looper對象,它是一個ThreadLocal
  2. Looper內部有一個消息隊列,loop()方法調用后線程開始不斷從消息隊列中取出消息執行
  3. Looper可以使一個線程變成Looper線程。

2. 異步處理大師 Handler

什么是handler?handler扮演了往MQ上添加消息和處理消息的角色(只處理由自己發出的消息),即通知MQ它要執行一個任務(sendMessage),并在loop到自己的時候執行該任務(handleMessage),整個過程是異步的。handler創建時會關聯一個looper,默認的構造方法將關聯當前線程的looper,不過這也是可以set的。默認的構造方法:

public class handler {

    final MessageQueue mQueue;  // 關聯的MQ
    final Looper mLooper;  // 關聯的looper
    final Callback mCallback; 
     // 其他屬性

    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());
            }
        }
        // 默認將關聯當前線程的looper
        mLooper = Looper.myLooper();
        // looper不能為空,即該默認的構造方法只能在looper線程中使用
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 重要!直接把關聯looper的MQ作為自己的MQ,因此它的消息將發送到關聯looper的MQ上
        mQueue = mLooper.mQueue;
        mCallback = null;
    }
    
    // 其他方法
}

下面咱們就可以為之前的LooperThread類加入Handler:

public class LooperThread extends Thread {
    private Handler handler1;
    private Handler handler2;

    @Override
    public void run() {
        // 將當前線程初始化為Looper線程
        Looper.prepare();
        
        // 實例化兩個handler
        handler1 = new Handler();
        handler2 = new Handler();
        
        // 開始循環處理消息隊列
        Looper.loop();
    }
}
handler和looper關系

Handler發送消息

有了handler之后,我們就可以使用以下這些方法向MQ上發送消息了。

  • post(Runnable)
  • postAtTime(Runnable, long)
  • postDelayed(Runnable, long)
  • sendEmptyMessage(int)
  • sendMessage(Message)
  • sendMessageAtTime(Message, long)
  • sendMessageDelayed(Message, long)

光看這些API可能會覺得handler能發兩種消息,一種是Runnable對象,一種是message對象,這是直觀的理解,但其實post發出的Runnable對象最后都被封裝成message對象了,見源碼:

// 此方法用于向關聯的MQ上發送Runnable對象,它的run方法將在handler關聯的looper線程中執行
    public final boolean post(Runnable r)
    {
       // 注意getPostMessage(r)將runnable封裝成message
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

    private final Message getPostMessage(Runnable r) {
        Message m = Message.obtain();  //得到空的message
        m.callback = r;  //將runnable設為message的callback,
        return m;
    }

    public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;  // message的target必須設為該handler!
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }

其他方法就不羅列了,總之通過handler發出的message有如下特點:

  1. message.target為該handler對象,這確保了looper執行到該message時能找到處理它的handler,即loop()方法中的關鍵代碼
    msg.target.dispatchMessage(msg);
  2. post發出的message,其callback為Runnable對象

Handler處理消息

說完了消息的發送,再來看下handler如何處理消息。消息的處理是通過核心方法dispatchMessage(Message msg)與鉤子方法handleMessage(Message msg)完成的,見源碼

// 處理消息,該方法由looper調用
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            // 如果message設置了callback,即runnable消息,處理callback!
            handleCallback(msg);
        } else {
            // 如果handler本身設置了callback,則執行callback
            if (mCallback != null) {
                 /* 這種方法允許讓activity等來實現Handler.Callback接口,避免了自己編寫handler重寫handleMessage方法。見http://alex-yang-xiansoftware-com.iteye.com/blog/850865 */
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            // 如果message沒有callback,則調用handler的鉤子方法handleMessage
            handleMessage(msg);
        }
    }
    
    // 處理runnable消息
    private final void handleCallback(Message message) {
        message.callback.run();  //直接調用run方法!
    }
    // 由子類實現的鉤子方法
    public void handleMessage(Message msg) {
    }

可以看到,除了handleMessage(Message msg)和Runnable對象的run方法由開發者實現外(實現具體邏輯),handler的內部工作機制對開發者是透明的。這正是handler API設計的精妙之處!

Handler的用處

  • handler可以在任意線程發送消息,這些消息會被添加到當前線程looper關聯的MQ上。
handler發送消息
  • handler是在與它關聯的looper線程中處理消息

handler處理消息

這就解決了android最經典的不能在其他非主線程中更新UI的問題。android的主線程也是一個looper線程(looper在android中運用很廣),我們在其中創建的handler默認將關聯主線程MQ。因此,利用handler的一個solution就是在activity中創建handler并將其引用傳遞給worker thread,worker thread執行完任務后使用handler發送消息通知activity更新UI。(過程如圖)

消息處理全過程

下面給出sample代碼,僅供參考:

public class TestDriverActivity extends Activity {
    private TextView textview;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textview = (TextView) findViewById(R.id.textview);
        // 創建并啟動工作線程
        Thread workerThread = new Thread(new SampleTask(new MyHandler()));
        workerThread.start();
    }
    
    public void appendText(String msg) {
        textview.setText(textview.getText() + "\n" + msg);
    }
    
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            String result = msg.getData().getString("message");
            // 更新UI
            appendText(result);
        }
    }
}
public class SampleTask implements Runnable {
    private static final String TAG = SampleTask.class.getSimpleName();
    Handler handler;
    
    public SampleTask(Handler handler) {
        super();
        this.handler = handler;
    }

    @Override
    public void run() {
        try {  // 模擬執行某項任務,下載等
            Thread.sleep(5000);
            // 任務完成后通知activity更新UI
            Message msg = prepareMessage("task completed!");
            // message將被添加到主線程的MQ中
            handler.sendMessage(msg);
        } catch (InterruptedException e) {
            Log.d(TAG, "interrupted!");
        }

    }

    private Message prepareMessage(String str) {
        Message result = handler.obtainMessage();
        Bundle data = new Bundle();
        data.putString("message", str);
        result.setData(data);
        return result;
    }

}

封裝任務 Message

在整個消息處理機制中,message又叫task,封裝了任務攜帶的信息和處理該任務的handler。message的用法比較簡單,這里不做總結了。但是有這么幾點需要注意:

1.盡管Message有public的默認構造方法,但是你應該通過Message.obtain()來從消息池中獲得空消息對象,以節省資源。具體Message源碼分析請參考 管理與分配內存

2.如果你的message只需要攜帶簡單的int信息,請優先使用Message.arg1和Message.arg2來傳遞信息,這比用Bundle更省內存

3.擅用message.what來標識信息,以便用不同方式處理message。

到此為止了,Android消息處理機制差不多就講完了,好累,有木有打賞的?

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

推薦閱讀更多精彩內容