Handler Messsage基本功能介紹
Handler Message是安卓系統(tǒng)提供不同線程間通訊的一種機(jī)制。其中handler負(fù)責(zé)發(fā)送消息纽门,處理消息,Message 負(fù)責(zé)攜帶數(shù)據(jù),MessageQueue負(fù)責(zé)存儲(chǔ)消息,以隊(duì)列的形式對(duì)外提供插入和刪除操作悔叽。Looper負(fù)責(zé)循環(huán)從MessageQueue取消息。
源碼解析
首先看一下handler發(fā)送消息的幾種用法
// post有兩種方法
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
//sendEmptyMessage有兩種方法
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);
}
//sendMessage有兩種方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
根據(jù)上述代碼得知爵嗅,以上前五種方法最后都會(huì)調(diào)用sendMessageDelayed(msg,delayMillis);所以這幾種方法在本質(zhì)上并沒(méi)有區(qū)別娇澎,只不過(guò)使用方式有所區(qū)別。
接下來(lái)我們看一下Looper是怎么創(chuàng)建的
通過(guò)流程圖得知睹晒,在主線程的main方法里調(diào)用了Looper.prepareMainLooper方法
public static void main(String[] args) {
...
//創(chuàng)建Looper對(duì)象
Looper.prepareMainLooper();
...
//循環(huán)取消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
public static void prepareMainLooper() {
//一個(gè)靜態(tài)內(nèi)部類創(chuàng)建Looper 保證單個(gè)線程Looper唯一性
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//將創(chuàng)建的Looper對(duì)象方法threadLocal Map對(duì)象里趟庄,map的key是UI線程
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
prepareMainLooper()方法調(diào)用了prepare()方法,prepare方法通過(guò)new Looper()創(chuàng)建了Looper對(duì)象并放在了threadLocal里面伪很。
然后我們看一下new Handler() 做了哪些事情呢戚啥?
由上圖得知,我們?cè)趎ew Handler構(gòu)造方法里锉试,分別獲取了mLooper對(duì)象和MessageQueue對(duì)象猫十,這兩個(gè)對(duì)象也就是ActivityThread 中mian方法所創(chuàng)建的,這也就是為什么子線程不能直接new handler()呆盖。
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());
}
}
//因?yàn)橹骶€程已經(jīng)創(chuàng)建了looper拖云,所以這里可以直接獲取到,而子線程是不能直接獲取的
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
//獲取消息隊(duì)列应又,一個(gè)消息隊(duì)列綁定一個(gè)Looper對(duì)象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
然后我們看一下handler內(nèi)部是如何發(fā)送消息的?
由上圖得知宙项,handler在sendMessage()之后,msg最終存到了MessageQueue里面株扛,MessageQueue里面有一個(gè)mMessages全局變量尤筐,傳過(guò)來(lái)的Msg賦值給了這個(gè)變量。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
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賦值
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;
}
最后handler是如何取消息的呢洞就?
在ActivityThread的main方法里面除了有一個(gè)Looper.prepareMainLooper()還有個(gè)Looper.loop方法叔磷,這是一個(gè)輪詢方法,無(wú)限循環(huán)的從MessageQueue里面取消息奖磁,并通過(guò)handler里面的dispatchMessage()方法將msg返回。(這里值得注意的是這個(gè)loop方法雖然是死循環(huán)繁疤,但是并不會(huì)造成ANR是因?yàn)檫@里調(diào)用了ndk里面的JNI方法咖为,使主線程釋放CPU資源進(jìn)入休眠狀態(tài))
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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
//從MessageQueue里面取msg
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 traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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);
}
msg.recycleUnchecked();
}
}
//通過(guò)dispatchMessage方法將msg傳出去
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//對(duì)應(yīng)handler.post()方法
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
另外補(bǔ)充一下常見(jiàn)面試問(wèn)題:
1.Handler是如何實(shí)現(xiàn)線程切換的?
答:其實(shí)就是這個(gè)消息發(fā)送的過(guò)程稠腊,我們?cè)诓煌木€程發(fā)送消息躁染,線程之間的資源是共享的。也就是任何變量在任何線程都可以修改架忌,只要做并發(fā)操作就好了吞彤。插入隊(duì)列就是加鎖的synchronized,Handler中我們使用的是同一個(gè)MessageQueue對(duì)象,同一時(shí)間只能一個(gè)線程對(duì)消息進(jìn)行入隊(duì)操作饰恕。handler在子線程通過(guò)sendMessage將消息存儲(chǔ)到隊(duì)列中后挠羔,主線程的Looper還在一直循環(huán)loop()處理。這樣主線程就能拿到子線程存儲(chǔ)的Message對(duì)象埋嵌,也就完成了線程的切換破加。
- handler 是如何實(shí)現(xiàn)延時(shí)發(fā)送消息的?
答:MessageQueue中enqueueMessage方法主要負(fù)責(zé)將從handler發(fā)送過(guò)來(lái)的message根據(jù)when的大小來(lái)添加到單向鏈表中雹嗦,when的數(shù)據(jù)越大在鏈表中的位置越靠后范舀,delay消息會(huì)一直阻塞線程,直到延遲走完了罪,或者下一個(gè)消息到來(lái)锭环。
至此我們對(duì)handle message整個(gè)流程有了一個(gè)完整的分析,相信以后再使用handler的時(shí)候會(huì)有一個(gè)更清晰的認(rèn)識(shí)泊藕。