android Handler機制
##Handler簡述
主要用於線程間通訊,Handler 允許發送或執行消息(Message)。android UI線程中不能執行耗時操作(導致ANR),耗時的任務放到子線程中處理,處理完可以通過拿到主線程的handler進行發送消息進行入消息隊列(MessageQueue),主線程的Looper會一直取消息隊列的消息進行處理,處理消息的時候先拿到消息綁定的handler對象(message.target) 調用dispatchMessage方法通知handler進行處理消息
首先我們提出兩個問題
- 子線程發送的消息爲什麼到了handler的handleMessage回調方法就可以更新UI了
- Handler發送的消息最終怎麼調用handler的handleMessage方法的
下面通過閱讀Handler相關源代碼來尋找答案
爲了我們能更好的使用Handler 瞭解handler的原理是有必要的
handler機制相關類
- Handler
- Looper
- MessageQueue
- Message
我們先摸出主流程,細枝末節在慢慢分析
平常我們是這樣使用Handler
第一步 在Activity中創建Handler
Handler handler =new Handler(){
public void handleMessage(){
//todo 處理一些ui操作
}
}
第二步 使用Handler去發消息
//此處在子線程中調用
public void sendMessage(String conent){
Message message=new Message();
message.what=1;
message.obj=content;
handler.sendMessage(message);
}
handlerMessage方法爲什麼可以更新UI,我們猜想下更新UI需要在主線程中,是不是handlerMessage就是在主線程中回調的。繼續往下看:)
Handler.java handler調用sendMessage方法
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
Handler.java sendMessage->sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
Handler.java sendMessageDelayed->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);
}
sendMessageAtTime方法中出現新的對象mQueue,需要看下這個對象是哪裏來的,這是handler持有的一個MessageQueue對象 使用的handler的時候我們只是new了一個Handler和調用sendMessage方法
Handler.java 先看new Handler() 這個無參構造函數
public Handler() {
this(null, false);
}
繼續看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());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
我們看到mQueue通過mLooper.mQueue拿到的,mLooper通過Looper.myLooper()獲取的,接下來跟蹤mLooper.mQueue是在哪裏賦值
獲取Looper的方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
從代碼中可以發現Looper對象是從sThreadLocal中得到
我們嘗試搜一下sThreadLocal.set 發現這個麼個函數
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));
}
繼續看new Looper(quitAllowed) 構造函數
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
原來Handler持有mQueue(MessageQueue) 是創建Looper的時候初始化的,繼續向下分析
Handler.java sendMessageAtTime->enqueueMessage
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target保存了當前對象handler的引用
MessageQueue.java enqueueMessage方法
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;
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;
}
}
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;
}
從方法名稱可以看出enqueue入隊 外層穿入的msg入一個消息隊列,具體怎麼入的 有興趣的大家可以到網上查查資料
這裏只需要知道發送的message被存到了MessageQueue對象中
看到這裏你可能會很奇怪這不是結束了嚒,怎麼沒看到調用handleMessage方法呀,看官別急 下面還有呢!
既然消息已經被存起來了肯定有一個地方使用吧 還記得前面我拋出的4個類嘛(Handler,Looper,MessageQueue,Message)通過上面分析MessageQueue是在Looper中創建的 我們到Looper類看看
先搜下mQueue使用的地方,發現了這個函數
public static void loop() {
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;
// 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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);
}
msg.recycleUnchecked();
}
}
裏面有這麼一行代碼 Message msg = queue.next() 哈哈看到這裏是不是猜出下面要做什麼
通過MessageQueue拿到msg消息,然後使用的msg.target.dispatchMessage(msg);
我們看下target.dispatchMessage(msg)做了什麼事情
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
看到這裏相信看官就明白了 原來handleMessage方法是在dispatchMessage調用的
dispatchMessage是在Looper.loop方法中調用的順序是:
1.從MessageQueue拿到msg
2.使用msg綁定的Handler對象調用dispatchMessage方法處理消息
如果handleMessage是在主線程中調用的 是不是Looper.loop應該也在主線中調用的呀
這時候你會很奇怪Looper.loop我從來都沒有用過,別急繼續往下看
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
android 系統啓動的時候會默認創建一個Looper.prepareMainLooper(); 然後調用Looper.loop();方法進行處理消息隊列的消息,Looper.loop();調用所在線程正是ActivityThread(主線程)
總結一下
1.創建Looper時候 looper會創建一個MessageQueue進行持有
2.handler發送的消息的時候會將會把自己和Message綁定起來msg.target=this,使用MessageQueue進行入消息隊列
3.Looper有一個靜態的loop方法 輪訓調用MessageQueue的next()方法獲取消息
4.msg.target.dispatchMessage(msg);處理消息
5.dispatchMessage最終調用handleMessage方法將消息回調給上層
拓展一:handler.post回調方法是在主線程中執行的(不能做耗時操作)
有的同學一看到Runnable 第一感覺是子線程中執行的 : ) 我只笑笑不說話 哈哈
調用順序
1.構建一個Message
2.message的callback變量持有Runnable接口引用
3.使用sendMessageDelayed發送消息
msg.target.dispatchMessage(msg)的時候會先判斷message 的callback變量是否爲空 如果不爲空則使用message.callback調用run()方法
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static void handleCallback(Message message) {
message.callback.run();
}