Handler是Android中消息傳遞機制,可以將工作線程所創(chuàng)建的消息傳遞到主線程中去處理懦傍,進行UI更新或者其他需要在主線程進行處理的工作÷樱總的來說粗俱,就是線程之間的通訊。
Handler原理解析
了解Handler原理之前虚吟,我們需要先了解幾個相關(guān)的類
- Hander (主要作用發(fā)送和處理消息和Runnable)
- Message (線程間消息傳遞的載體)
- MessageQueue(消息隊列寸认,存放消息)
- Looper (循環(huán)讀取消息隊列,發(fā)送到指定Handler處理)
Handler的基本使用
//在主線程創(chuàng)建一個Handler對象
//并重載handleMessage方法
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message){
//需要在mHandler的線程處理的業(yè)務(wù)邏輯
//可以根據(jù)Message的參數(shù)處理相應(yīng)業(yè)務(wù)串慰,例如UI更新
textView.setText("通過sendMessage更新UI")
}
}
//然后在子線程中發(fā)送消息
//通過sendMessage方法發(fā)送
new Thread(new Runnable(){
@Override
public void run(){
//主線的Handler
Message message = new Message();
message.what = 1;
message.obj = "可以傳遞對象偏塞,這里是傳遞字符串對象";
//通過sendMessage發(fā)送消息對象
mHandler.sendMessage(message)
}
}).start();
//或者可以傳遞一個Runnable對象
new Thread(new Runnable(){
@Override
public void run(){
mHandler.post(new Runnable(){
@Override
public void run(){
//需要在mHandler的線程處理的業(yè)務(wù)邏輯
//如更新UI
textView.setText("通過post更新UI")
}
})
}
})
除了上面2種方法,Handler發(fā)送消息很多種
//發(fā)送Runnable
post(Runnable)
postAtTime(Runnable,long)
postAtTime(Runnable,Object,long)
postDelayed(Runnable,long)
postDelayed(Runnable,Object,long)
//發(fā)送Message
sendMessage(Message)
sendMessageDelayed(Message,long)
sendMessageAtTime(Message,long)
sendMessageAtFrontOfQueue(Message)
sendEmptyMessage(int)
sendEmptyMessageDelayed(int,long)
sendEmptyMessageAtTime(int,long)
//我們先分析比較簡單的sendMessage和post
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
//調(diào)用成員方法sendMessageDelayed邦鲫,延時為0
public final boolean sendMessageDelayed(Message msg, long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
//所以插入消息隊列的時候就是(當前時間+0)
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//uptimeMellis就是消息傳遞到Handler的時間
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
MessageQueue queue = mQueue;
//省略部分代碼...
//最終通過enqueueMessage把消息插入到消息隊列
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//把當前Handler對象引用保存在Message.target灸叼,后續(xù)通過這個target來傳遞到指定Handler去處理消息
msg.target = this;
//設(shè)置Message是否異步Message
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//插入到消息隊列
return queue.enqueueMessage(msg, uptimeMillis);
}
//MessageQueue.java#enqueueMessage
boolean enqueueMessage(Message msg, long when) {
//省略部分代碼...
synchronized (this) {
//省略部分代碼...
msg.markInUse();//標記Message為使用中
msg.when = when;//執(zhí)行時間
Message p = mMessages;//消息隊列鏈頭部
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
//遍歷消息隊列神汹,尋找插入Message的位置
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//插入到消息隊列
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
//喚醒
nativeWake(mPtr);
}
}
return true;
}
//sendMessage基本流程就如上所示
//sendMessage -> sendMessageDelayed -> sendMessageAtTime -> enqueueMessage
//接著看post流程
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
//調(diào)用getPostMessage把Runnable封裝為Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
//最后流程還是sendMessage流程一致
通過上面的代碼,了解了Handler如何發(fā)送消息的方法古今,那么線程之間消息是如何傳遞的呢屁魏?
為什么在其他線程通過Hander發(fā)送消息后,會到Handler線程進行處理捉腥?
首先先看創(chuàng)建Hander實例時候處理
Handler mHandler = new Handler()//創(chuàng)建了Handler實例
//Handler.java
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
...
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;
...
}
//Handler構(gòu)造方法主要工作:
//獲取Looper對象
//從Looper對象獲取mQueue(消息隊列)
Looper對象獲取
//Looper.java
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
//通過ThreadLocal.get獲取Looper對象
return sThreadLocal.get();
}
ThreadLoal變量氓拼,線程局部變量,簡單理解為線程私有變量抵碟,這里就不展開描述桃漾;
myLooper方法中通過sThreadLocal.get()獲取Looper,那Looper是在什么時候set進去的拟逮?通過sThreadLocal.set關(guān)鍵字搜索呈队,在Looper的prepare方法內(nèi)找到
//一般線程初始化Looper
public static void prepare() {
prepare(true);
}
//主線程初始化Looper
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
//真正初始化Looper方法
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//創(chuàng)建Looper對象,并將set到ThreadLocal
sThreadLocal.set(new Looper(quitAllowed));
}
//Looper構(gòu)造方法
private Looper(boolean quitAllowed) {
//創(chuàng)建MessageQueue
mQueue = new MessageQueue(quitAllowed);
//記錄線程ID
mThread = Thread.currentThread();
}
所以要創(chuàng)建Handler對象唱歧,必定要先調(diào)用Looper對象的prepare或者prepareMainLooper方法,否則在Handler構(gòu)造方法就會跑出異常粒竖,因為Looper.myLooper返回的對象為null
public Handler(Callback callback, boolean async) {
···
mLooper = Looper.myLooper();
if (mLooper == null) {
//獲取到Looper對象為空颅崩,拋出異常
//報錯說明未調(diào)用Looper.prepare()
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
···
}
那Looper.prepare方法在什么時候調(diào)用?了解過Android源碼的可能知道蕊苗,在ActivityThread的main方法中沿后,調(diào)用了Looper.prepareMainLooper,而且當前線程也就是我們所說的主線程
ActivityThread.java
public static void main(String[] args) {
···
//初始化Looper對象
Looper.prepareMainLooper();
···
//開始循環(huán)讀取消息
Looper.loop();
···
}
既然我們要循環(huán)從消息隊列獲取消息進行發(fā)送朽砰,那就可能到開啟循環(huán)尖滚,Looper.loop方法的作用就是循環(huán)從消息隊列讀取消息并且發(fā)送。通過源碼看看Looper.loop方法是如何循環(huán)讀取消息
Looper.java
public static void loop() {
//獲取當前線程的Looper對象
final Looper me = myLooper();
···
//獲取Looper的消息隊列
final MessageQueue queue = me.mQueue;
···
//開始循環(huán)獲取消息
for (;;) {
//獲取消息隊列瞧柔,可能會阻塞
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
···
try {
//分發(fā)到指定Handler去處理消息
//msg.target就是前面sendMessage中設(shè)置的Handler引用
msg.target.dispatchMessage(msg);
···
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
···
//回收Message對象
msg.recycleUnchecked();
}
}
知道了Message如何分發(fā)到指定Handler漆弄,跟蹤dispatchMessage看看最后如何傳遞到Hander的handleMessage方法
//Handler.java#dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//判斷Runnable對象存在
handleCallback(msg);
} else {
//可以在構(gòu)造方法傳入Callback,作用和handlerMessage一樣
//一般都直接重寫handleMessage方法
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//最終調(diào)用handlerMessage造锅,把消息傳遞到我們實例話的Handler對象撼唾,一般我們都會重寫handleMessage方法
handleMessage(msg);
}
}
總結(jié)
Handler消息傳遞機制使用之前,需要先初始化Looper綁定當前線程哥蔚,再循環(huán)從消息隊列獲取消息分發(fā)到指定的Handler去處理倒谷,以上只分析了Handerl機制的一般用法,還有其他如異步消息糙箍,IdleHandlder的用法還未涉及渤愁,后續(xù)逐步進行分析