在Android開發(fā)中践瓷,是不能在子線程中更新UI的换衬,這一點想必大家都知道痰驱,但是证芭,很多時候在子線程中訪問了網絡或做其它耗時處理后,希望可以把結果更新到UI中担映。于是废士,Android 中提供了一個Handler機制。它很好的解決了這個問題另萤。
在分析Handler之前湃密,先簡單說下幾個關鍵類:
- Handler:負責消息的發(fā)送和處理。
- Message:消息載體四敞,用于保存消息的arg、內容等拔妥。
- MessageQueue:消息隊列忿危,用于存放消息載體Message。
- Looper:可以看成是一個消息輪詢器没龙,會不斷的從MessageQueue中取出Message
1铺厨、Handler的使用
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 1){
//接收消息并處理
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "消息";
handler.sendMessage(message);
}
}).start();
從代碼看,Handler的使用很簡單硬纤,在子線程中創(chuàng)建一個Message對象解滓,通過handler.sendMessage()發(fā)送,然后在Handler內的handleMessage()中進行處理筝家。但是洼裤,在實際開發(fā)中創(chuàng)建Handler時,建議大家選用以靜態(tài)內部類的方式來創(chuàng)建Handler溪王,這樣可以降低內存泄漏的發(fā)生腮鞍。接下來看一下Handler的構造函數(shù)。
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());
}
}
mLooper = Looper.myLooper();
//1
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;
}
在第二個構造函數(shù)注釋1處莹菱,可以發(fā)現(xiàn):如果當前線程中mLooper 為null移国,會拋出RuntimeException,這也就是為什么在子線程中創(chuàng)建Handler需要先Looper.prepare()的原因道伟。而主線程不用我們手動創(chuàng)建Looper對象迹缀,是因為在啟動程序時已經為主線程創(chuàng)建了Looper對象∶刍眨看下面一段ActivityThread類中的main方法:
public static void main(String[] args) {
//省略代碼...........
//為主線程創(chuàng)建一個Looper對象
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");
}
在程序啟動時祝懂,不單單是為主線程創(chuàng)建了一個Looper對象,而且還啟動的消息輪詢器Looper.loop()娜汁。接下來我們先分析sendMessage(),看看消息是怎么加進MessageQueue中的嫂易。
2、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);
}
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);
}
通過上面一系列代碼下來掐禁,可以發(fā)現(xiàn):sendMessage()發(fā)送消息后怜械,最后會調用MessageQueue的enqueueMessage()方法颅和,uptimeMillis是發(fā)送消息的時間。
//MessageQueue類的enqueueMessage()
boolean enqueueMessage(Message msg, long when) {
//1
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) {
//如果調用了Looper#quit()或Looper#quitSafely(),會結束輪詢缕允,并釋放資源
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;
}
在上面的代碼注釋1處峡扩,首先判斷msg.target是否為null,根據Handler中的enqueueMessage()方法障本,可以發(fā)現(xiàn)msg.target是Message 內的一個Handler類變量教届。然后判斷消息輪詢是否結束,如果沒有驾霜,則加入消息隊列案训。到此,消息的添加就完畢了粪糙。
3强霎、Looper分析
首先,Looper的創(chuàng)建
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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");
}
//1
sThreadLocal.set(new Looper(quitAllowed));
}
prepareMainLooper()是在主線程創(chuàng)建Looper時調用的蓉冈,最終也是調用了prepare()城舞。在上面代碼的注釋1處,sThreadLocal是ThreadLocal的一個實例對象寞酿。sThreadLocal內部以當前線程作為key家夺,創(chuàng)建的Looper實例作為value。主要在ThreadLocal的內部類ThreadLocalMap中實現(xiàn)伐弹。這樣使得每個線程都有一個獨立的Looper實例副本拉馋。
Looper#loop()
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 (;;) {
//1
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 {
//2
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();
}
}
在注釋1處,可以發(fā)現(xiàn):looper利用for(;;)進入了無限循環(huán)掸茅。調用MessageQueue 中next()方法椅邓,會向MessageQueue 中取出消息,如果沒有消息存在昧狮,next()會處于阻塞狀態(tài)(這里是由底層實現(xiàn)的景馁,調用了本地方法nativePollOnce()),當有消息返回時逗鸣,會走到注釋2處合住,調用Handler的dispatchMessage()進行分發(fā)消息。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handleCallback()是在調用Handler#post(Runnable run)或者是設置了msg.callback時回調的撒璧。最后回調了 handleMessage()透葛。
完篇~