Handler消息機制相關類介紹
- Message:是在線程之間傳遞的消息,它可以在內部攜帶少量的消息,用於在不同線程之間交換數據。
- Handler:處理者的意思,它主要是用於發送和處理消息。發送消息一般使用Handler的sendMessage()方法,接收消息使用Handler的handleMessage()方法。
- MessageQueue:消息隊列的意思,它主要用於存放所有通過Handler發送的消息,每個線程中只會有一個MessageQueue對象。
- Looper:是每個線程的MessageQueue管家,調用Looper的Loop方法,就會進入到一個無限循環當中,然後每當發現MessageQueue中存在一條消息,就會將它取出並傳遞到Handler的handleMessage()方法中,每一個線程也只會有一個Looper對象。
- ThreadLocal:是一個線程內部的數據存儲類,通過它可以在指定的線程中存儲數據,數據存儲以後,只有在指定線程中可以獲取到存儲的數據,對於其他線程來說則無法獲取到數據。線程本地變量,存放Looper對象。每個線程對應自己的Looper。
Message的生成
- new Message()
- Message.obtain()
- Handler.obtain()
Handler 類
Handler handler = new Handler() { // 匿名子類對象(),調用父類默認的構造函數
public void handleMessage(Message msg) {
// 更新UI操作
}
}
// Handler類的默認構造函數
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
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 的靜態方法myLooper(),獲取到本線程的Looper對象,如果是在主線程中,則設置Looper對象是在ActivityThread類的main()方法中設置。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 獲取MessageQueue對象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
ActivityThread 類中的main方法如下:
public static final void main(String[] args) {
...
//Looper對象的初始化,放到線程本地變量中
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler();
}
....
//輪詢器輪詢取消息
Looper.loop();
....
}
}
Looper 類
// 創建線程本地變量,存放Looper對象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
// 初始化主線程的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();
}
}
// 參數quitAllowed false:不允許中斷;true:允許中斷
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
// 把Looper對象保存到ThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
// Looper的構造方法
private Looper(boolean quitAllowed) {
// 創建MessageQueue對象,並設置是否可以中斷
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
// 調用此方法創建Looper,是可以中斷的
public static void prepare() {
prepare(true);
}
Handler 發送消息
// 1、handler對象 sendMessage()
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
// 2、
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
// SystemClock.uptimeMillis() 獲取系統的時間,從開機時間算起
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
// 3、
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
// 獲取MessageQueue對象
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);
}
// 4、
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
// this 就是當前Handler對象,把Handler對象給msg對象的target屬性
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
// 消息隊列按照消息的進入順序和發送時間排序,喚醒looper輪詢器
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue 插入消息
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
// 如果消息爲空,或者獲取當前消息的時間爲0,或者當前消息的時間比消息隊列的第一個消息的時間小,則把當前消息插入到消息隊列的頭部
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;
for (;;) {
prev = p;
// 獲取下一個消息
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 插入消息,Message是一個單鏈表形式,要找到插入消息的前一個位置和後一個位置
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;
}
Looper 輪詢器取消息
public static void loop() {
// 獲取當前的Looper對象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 獲取MessageQueue對象
final MessageQueue queue = me.mQueue;
// 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(); // might block
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);
}
// 1、msg.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);
}
// 2、消息回收利用
msg.recycleUnchecked();
}
}
MessageQueue next()方法取消息
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
// 如果當前時間,小於msg的時間,則等待並計算等待時間
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
// 從消息隊列中取出消息頭
mMessages = msg.next;
}
// 把取出的消息的next設置爲null,取消與下一個節點的關聯
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
Handler dispatchMessage()處理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 如果設置了消息的callback,則處理callback
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// 走handleMessage方法處理消息
handleMessage(msg);
}
}
// 回調callback的run方法
private static void handleCallback(Message message) {
message.callback.run();
}
// handler的handleMessage空方法,讓子類去實現,處理業務邏輯
public void handleMessage(Message msg) {
}
Message 消息回收
// 消息回收方法
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
// 消除message消息對象裏的屬性值
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) { // 就是Object對象滿足synchronized語法
if (sPoolSize < MAX_POOL_SIZE) { // MAX_POOL_SIZE=50
next = sPool; // 設置新的回收消息的下一個爲sPool
sPool = this; // 設置該消息爲新的消息頭
sPoolSize++; // 回收的消息+1
}
}
}
Handler消息機制流程圖
在子線程中使用Handler機制
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare(); // 創建Looper對象
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop(); // 開啓Looper輪詢器,讀取消息,沒有消息則等待
* }
* }