概述
Handler是Android消息機制的上層接口。通過它可以輕松地將一個任務切換到Handler所在的線程中去執行。通常情況下,Handler的使用場景就是 更新UI
。
Handler的使用
在子線程中,進行耗時操作,執行完操作后,發送消息,通知主線程更新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() {
// 執行耗時任務 ...
// 任務執行完后,通知Handler更新UI
Message message = Message.obtain();
message.what = 1;
mHandler.sendMessage(message);
}
}
).start();
}
}
Handler架構
Handler消息機制主要包括: MessageQueue
、 Handler
、 Looper
這三大部分,以及 Message
。
- Message:需要傳遞的消息,可以傳遞數據;
-
MessageQueue:消息隊列,但是它的內部實現并不是用的隊列,而是通過單鏈表的數據結構來維護消息列表,因為單鏈表在插入和刪除上比較有優勢。主要功能是向消息池投遞消息(
MessageQueue.enqueueMessage
)和取走消息池的消息(MessageQueue.next
)。 -
Handler:消息輔助類,主要功能是向消息池發送各種消息事件(
Handler.sendMessage
)和處理相應消息事件(Handler.handleMessage
); -
Looper:消息控制器,不斷循環執行(
Looper.loop
),從MessageQueue中讀取消息,按分發機制將消息分發給目標處理者。
從上面的類圖可以看出:
- Looper有一個MessageQueue消息隊列;
- MessageQueue有一組待處理的Message;
- Message中記錄發送和處理消息的Handler;
- Handler中有Looper和MessageQueue。
MessageQueue、Handler和Looper三者之間的關系: 每個線程中只能存在一個Looper,Looper是保存在ThreadLocal中的。 主線程(UI線程)已經創建了一個Looper,所以在主線程中不需要再創建Looper,但是在其他線程中需要創建Looper。 每個線程中可以有多個Handler,即一個Looper可以處理來自多個Handler的消息。 Looper中維護一個MessageQueue,來維護消息隊列,消息隊列中的Message可以來自不同的Handler。
Handler的運行流程
在子線程執行完耗時操作,當Handler發送消息時,將會調用 MessageQueue.enqueueMessage
,向消息隊列中添加消息。 當通過 Looper.loop
開啟循環后,會不斷地從消息池中讀取消息,即調用 MessageQueue.next
, 然后調用目標Handler(即發送該消息的Handler)的 dispatchMessage
方法傳遞消息, 然后返回到Handler所在線程,目標Handler收到消息,調用 handleMessage
方法,接收消息,處理消息。
源碼分析
在子線程創建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();
}
}
從上面可以看出,在子線程中創建Handler之前,要調用 Looper.prepare()
方法,Handler創建后,還要調用 Looper.loop()
方法。而前面我們在主線程創建Handler卻不要這兩個步驟,因為系統幫我們做了。
主線程的Looper
在ActivityThread的main方法,會調用
Looper.prepareMainLooper()
來初始化Looper,并調用Looper.loop()
方法來開啟循環。
public final class ActivityThread extends ClientTransactionHandler {
// ...
public static void main(String[] args) {
// ...
Looper.prepareMainLooper();
// ...
Looper.loop();
}
}
Looper
從上可知,要使用Handler,必須先創建一個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();
}
// ...
}
從上可以看出,不能重復創建Looper,每個線程只能創建一個。創建Looper,并保存在 ThreadLocal
。其中ThreadLocal是線程本地存儲區(Thread Local Storage,簡稱TLS),每個線程都有自己的私有的本地存儲區域,不同線程之間彼此不能訪問對方的TLS區域。
開啟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主循環方法
for (;;) {
Message msg = queue.next();
// 可能會阻塞,因為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
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,然后分發Message
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
}
finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// ...
msg.recycleUnchecked();
}
}
}
Handler
創建Handler:
public class Handler {
// ...
public Handler() {
this(null, false);
}
public Handler(Callback callback, Boolean async) {
// ...
// 必須先執行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;
// 設置消息是否為異步處理方式
}
}
發送消息:
子線程通過Handler的post()方法或send()方法發送消息,最終都是調用
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);
}
分發消息
在loop()方法中,獲取到下一條消息后,執行
msg.target.dispatchMessage(msg)
,來分發消息到目標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();
}
}