Android消息機(jī)制Handler深入理解
概述
Handler是Android消息機(jī)制的上層接口。通過它可以輕松地將一個(gè)任務(wù)切換到Handler所在的線程中去執(zhí)行。通常情況下,Handler的使用場景就是更新UI。
Handler的使用
在子線程中,進(jìn)行耗時(shí)操作,執(zhí)行完操作后,發(fā)送消息,通知主線程更新UI。
public class Activity extends android.app.Activity { private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); // 更新UI } } ; @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { // 執(zhí)行耗時(shí)任務(wù) ... // 任務(wù)執(zhí)行完后,通知Handler更新UI Message message = Message.obtain(); message.what = 1; mHandler.sendMessage(message); } } ).start(); } }
Handler架構(gòu)
Handler消息機(jī)制主要包括:MessageQueue、Handler、Looper這三大部分,以及Message。
- Message:需要傳遞的消息,可以傳遞數(shù)據(jù);
- MessageQueue:消息隊(duì)列,但是它的內(nèi)部實(shí)現(xiàn)并不是用的隊(duì)列,而是通過單鏈表的數(shù)據(jù)結(jié)構(gòu)來維護(hù)消息列表,因?yàn)閱捂湵碓诓迦牒蛣h除上比較有優(yōu)勢。主要功能是向消息池投遞消息( MessageQueue.enqueueMessage)和取走消息池的消息( MessageQueue.next)。
- Handler:消息輔助類,主要功能是向消息池發(fā)送各種消息事件( Handler.sendMessage)和處理相應(yīng)消息事件( Handler.handleMessage);
- Looper:消息控制器,不斷循環(huán)執(zhí)行( Looper.loop),從MessageQueue中讀取消息,按分發(fā)機(jī)制將消息分發(fā)給目標(biāo)處理者。
從上面的類圖可以看出:
- Looper有一個(gè)MessageQueue消息隊(duì)列;
- MessageQueue有一組待處理的Message;
- Message中記錄發(fā)送和處理消息的Handler;
- Handler中有Looper和MessageQueue。
MessageQueue、Handler和Looper三者之間的關(guān)系: 每個(gè)線程中只能存在一個(gè)Looper,Looper是保存在ThreadLocal中的。 主線程(UI線程)已經(jīng)創(chuàng)建了一個(gè)Looper,所以在主線程中不需要再創(chuàng)建Looper,但是在其他線程中需要?jiǎng)?chuàng)建Looper。 每個(gè)線程中可以有多個(gè)Handler,即一個(gè)Looper可以處理來自多個(gè)Handler的消息。 Looper中維護(hù)一個(gè)MessageQueue,來維護(hù)消息隊(duì)列,消息隊(duì)列中的Message可以來自不同的Handler。
Handler的運(yùn)行流程
在子線程執(zhí)行完耗時(shí)操作,當(dāng)Handler發(fā)送消息時(shí),將會(huì)調(diào)用 MessageQueue.enqueueMessage,向消息隊(duì)列中添加消息。 當(dāng)通過 Looper.loop開啟循環(huán)后,會(huì)不斷地從消息池中讀取消息,即調(diào)用 MessageQueue.next, 然后調(diào)用目標(biāo)Handler(即發(fā)送該消息的Handler)的 dispatchMessage方法傳遞消息, 然后返回到Handler所在線程,目標(biāo)Handler收到消息,調(diào)用 handleMessage方法,接收消息,處理消息。
源碼分析
在子線程創(chuàng)建Handler
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } } ; Looper.loop(); } }
從上面可以看出,在子線程中創(chuàng)建Handler之前,要調(diào)用 Looper.prepare()方法,Handler創(chuàng)建后,還要調(diào)用 Looper.loop()方法。而前面我們在主線程創(chuàng)建Handler卻不要這兩個(gè)步驟,因?yàn)橄到y(tǒng)幫我們做了。
主線程的Looper
在ActivityThread的main方法,會(huì)調(diào)用 Looper.prepareMainLooper()來初始化Looper,并調(diào)用 Looper.loop()方法來開啟循環(huán)。
public final class ActivityThread extends ClientTransactionHandler { // ... public static void main(String[] args) { // ... Looper.prepareMainLooper(); // ... Looper.loop(); } }
Looper
從上可知,要使用Handler,必須先創(chuàng)建一個(gè)Looper。
初始化Looper:
public final class Looper { 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)); } public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } private Looper(Boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } // ... }
從上可以看出,不能重復(fù)創(chuàng)建Looper,每個(gè)線程只能創(chuàng)建一個(gè)。創(chuàng)建Looper,并保存在 ThreadLocal。其中ThreadLocal是線程本地存儲(chǔ)區(qū)(Thread Local Storage,簡稱TLS),每個(gè)線程都有自己的私有的本地存儲(chǔ)區(qū)域,不同線程之間彼此不能訪問對方的TLS區(qū)域。
開啟Looper
public final class Looper { // ... public static void loop() { // 獲取TLS存儲(chǔ)的Looper對象 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; // 進(jìn)入loop主循環(huán)方法 for (;;) { Message msg = queue.next(); // 可能會(huì)阻塞,因?yàn)閚ext()方法可能會(huì)無線循環(huán) 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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } // ... final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0; final long dispatchEnd; try { // 獲取msg的目標(biāo)Handler,然后分發(fā)Message msg.target.dispatchMessage(msg); dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } // ... msg.recycleUnchecked(); } } }
Handler
創(chuàng)建Handler:
public class Handler { // ... public Handler() { this(null, false); } public Handler(Callback callback, Boolean async) { // ... // 必須先執(zhí)行Looper.prepare(),才能獲取Looper對象,否則為null mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; // 消息隊(duì)列,來自Looper對象 mCallback = callback; // 回調(diào)方法 mAsynchronous = async; // 設(shè)置消息是否為異步處理方式 } }
發(fā)送消息:
子線程通過Handler的post()方法或send()方法發(fā)送消息,最終都是調(diào)用 sendMessageAtTime()方法。
post方法:
public final Boolean post(Runnable r){ return sendMessageDelayed(getPostMessage(r), 0); } public final Boolean postAtTime(Runnable r, long uptimeMillis){ return sendMessageAtTime(getPostMessage(r), uptimeMillis); } public final Boolean postAtTime(Runnable r, Object token, long uptimeMillis){ return sendMessageAtTime(getPostMessage(r, token), uptimeMillis); } public final Boolean postDelayed(Runnable r, long delayMillis){ return sendMessageDelayed(getPostMessage(r), delayMillis); } private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
send方法:
public final Boolean sendMessage(Message msg){ return sendMessageDelayed(msg, 0); } public final Boolean sendEmptyMessage(int what){ return sendEmptyMessageDelayed(what, 0); } public final Boolean sendEmptyMessageDelayed(int what, long delayMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageDelayed(msg, delayMillis); } public final Boolean sendEmptyMessageAtTime(int what, long uptimeMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageAtTime(msg, uptimeMillis); } public final Boolean sendMessageDelayed(Message msg, long delayMillis){ if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } sendMessageAtTime() 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); } private Boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
分發(fā)消息
在loop()方法中,獲取到下一條消息后,執(zhí)行 msg.target.dispatchMessage(msg),來分發(fā)消息到目標(biāo)Handler。
public class Handler { // ... public void dispatchMessage(Message msg) { if (msg.callback != null) { // 當(dāng)Message存在回調(diào)方法,調(diào)用該回調(diào)方法 handleCallback(msg); } else { if (mCallback != null) { // 當(dāng)Handler存在Callback成員變量時(shí),回調(diào)其handleMessage()方法 if (mCallback.handleMessage(msg)) { return; } } // Handler自身的回調(diào)方法 handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); } }
總結(jié)
到此這篇關(guān)于深入理解Android消息機(jī)制Handler的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android調(diào)用OpenCV2.4.10實(shí)現(xiàn)二維碼區(qū)域定位
這篇文章主要為大家詳細(xì)介紹了Android調(diào)用OpenCV 2.4.10實(shí)現(xiàn)二維碼區(qū)域定位,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03Android獲取分享應(yīng)用列表詳解及實(shí)例
這篇文章主要介紹了Android獲取分享應(yīng)用列表詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-04-04Android如何優(yōu)雅的處理重復(fù)點(diǎn)擊
這篇文章主要介紹了Android如何優(yōu)雅的處理重復(fù)點(diǎn)擊,幫助大家更好的理解和學(xué)習(xí)使用Android開發(fā),感興趣的朋友可以了解下2021-03-03Android使用AudioRecord實(shí)現(xiàn)暫停錄音功能實(shí)例代碼
本篇文章主要介紹了Android使用AudioRecord實(shí)現(xiàn)暫停錄音功能實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-06-06Flutter Component動(dòng)畫的顯和隱最佳實(shí)踐
這篇文章主要為大家介紹了Flutter Component動(dòng)畫的顯和隱最佳實(shí)踐詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Android 自定義可拖拽View界面渲染刷新后不會(huì)自動(dòng)回到起始位置
這篇文章主要介紹了Android 自定義可拖拽View界面渲染刷新后不會(huì)自動(dòng)回到起始位置的實(shí)現(xiàn)代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02