Android消息機制Handler深入理解
概述
Handler是Android消息機制的上層接口。通過它可以輕松地將一個任務切換到Handler所在的線程中去執(zhí)行。通常情況下,Handler的使用場景就是更新UI。
Handler的使用
在子線程中,進行耗時操作,執(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í)行耗時任務 ...
// 任務執(zhí)行完后,通知Handler更新UI
Message message = Message.obtain();
message.what = 1;
mHandler.sendMessage(message);
}
}
).start();
}
}
Handler架構
Handler消息機制主要包括:MessageQueue、Handler、Looper這三大部分,以及Message。
- Message:需要傳遞的消息,可以傳遞數(shù)據(jù);
- MessageQueue:消息隊列,但是它的內部實現(xiàn)并不是用的隊列,而是通過單鏈表的數(shù)據(jù)結構來維護消息列表,因為單鏈表在插入和刪除上比較有優(yōu)勢。主要功能是向消息池投遞消息( MessageQueue.enqueueMessage)和取走消息池的消息( MessageQueue.next)。
- Handler:消息輔助類,主要功能是向消息池發(fā)送各種消息事件( Handler.sendMessage)和處理相應消息事件( Handler.handleMessage);
- Looper:消息控制器,不斷循環(huán)執(zhí)行( Looper.loop),從MessageQueue中讀取消息,按分發(fā)機制將消息分發(fā)給目標處理者。

從上面的類圖可以看出:
- Looper有一個MessageQueue消息隊列;
- MessageQueue有一組待處理的Message;
- Message中記錄發(fā)送和處理消息的Handler;
- Handler中有Looper和MessageQueue。
MessageQueue、Handler和Looper三者之間的關系: 每個線程中只能存在一個Looper,Looper是保存在ThreadLocal中的。 主線程(UI線程)已經(jīng)創(chuàng)建了一個Looper,所以在主線程中不需要再創(chuàng)建Looper,但是在其他線程中需要創(chuàng)建Looper。 每個線程中可以有多個Handler,即一個Looper可以處理來自多個Handler的消息。 Looper中維護一個MessageQueue,來維護消息隊列,消息隊列中的Message可以來自不同的Handler。

Handler的運行流程
在子線程執(zhí)行完耗時操作,當Handler發(fā)送消息時,將會調用 MessageQueue.enqueueMessage,向消息隊列中添加消息。 當通過 Looper.loop開啟循環(huán)后,會不斷地從消息池中讀取消息,即調用 MessageQueue.next, 然后調用目標Handler(即發(fā)送該消息的Handler)的 dispatchMessage方法傳遞消息, 然后返回到Handler所在線程,目標Handler收到消息,調用 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之前,要調用 Looper.prepare()方法,Handler創(chuàng)建后,還要調用 Looper.loop()方法。而前面我們在主線程創(chuàng)建Handler卻不要這兩個步驟,因為系統(tǒng)幫我們做了。
主線程的Looper
在ActivityThread的main方法,會調用 Looper.prepareMainLooper()來初始化Looper,并調用 Looper.loop()方法來開啟循環(huán)。
public final class ActivityThread extends ClientTransactionHandler {
// ...
public static void main(String[] args) {
// ...
Looper.prepareMainLooper();
// ...
Looper.loop();
}
}
Looper
從上可知,要使用Handler,必須先創(chuàng)建一個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();
}
// ...
}
從上可以看出,不能重復創(chuàng)建Looper,每個線程只能創(chuàng)建一個。創(chuàng)建Looper,并保存在 ThreadLocal。其中ThreadLocal是線程本地存儲區(qū)(Thread Local Storage,簡稱TLS),每個線程都有自己的私有的本地存儲區(qū)域,不同線程之間彼此不能訪問對方的TLS區(qū)域。
開啟Looper
public final class Looper {
// ...
public static void loop() {
// 獲取TLS存儲的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;
// 進入loop主循環(huán)方法
for (;;) {
Message msg = queue.next();
// 可能會阻塞,因為next()方法可能會無線循環(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的目標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;
// 消息隊列,來自Looper對象
mCallback = callback;
// 回調方法
mAsynchronous = async;
// 設置消息是否為異步處理方式
}
}
發(fā)送消息:
子線程通過Handler的post()方法或send()方法發(fā)送消息,最終都是調用 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ā)消息到目標Handler。
public class Handler {
// ...
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 當Message存在回調方法,調用該回調方法
handleCallback(msg);
} else {
if (mCallback != null) {
// 當Handler存在Callback成員變量時,回調其handleMessage()方法
if (mCallback.handleMessage(msg)) {
return;
}
}
// Handler自身的回調方法
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
}
總結

到此這篇關于深入理解Android消息機制Handler的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android調用OpenCV2.4.10實現(xiàn)二維碼區(qū)域定位
這篇文章主要為大家詳細介紹了Android調用OpenCV 2.4.10實現(xiàn)二維碼區(qū)域定位,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Android使用AudioRecord實現(xiàn)暫停錄音功能實例代碼
本篇文章主要介紹了Android使用AudioRecord實現(xiàn)暫停錄音功能實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-06-06
Android 自定義可拖拽View界面渲染刷新后不會自動回到起始位置
這篇文章主要介紹了Android 自定義可拖拽View界面渲染刷新后不會自動回到起始位置的實現(xiàn)代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-02-02

