本文假定讀者對Message. Loop. MessageQuene有一定了解各拷,從開發(fā)常規(guī)用法出發(fā)严蓖,從源碼的角度來理解android handler機制,然后做出自己的理解與總結(jié)土铺!
- 首先我們來看看Handler的習(xí)慣用法出刷。
//第一步:實例化Handler
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//處理收到的消息
if(msg.what==1){
}
return false;
}
});
//第二步:使用handler發(fā)送消息
private void sendMessage(){
Message message=Message.obtain();
message.what=1;
handler.sendMessage(message);
}
- 構(gòu)造方法: new Handler(Callback) 做了什么?
public Handler(Callback callback) {
this(callback, false);
}
//實際調(diào)用
public Handler(Callback callback, boolean async) {
// FIND_POTENTIAL_LEAKS的定義
//private static final boolean FIND_POTENTIAL_LEAKS = false;
//永遠為fasle 為什么要還這個代碼呢来氧?诫给!
//有知道的同學(xué)希望告訴一下!@惭铩中狂!
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());
}
}
//獲得Loop類
mLooper = Looper.myLooper();
//問題1:為什么mLoop不為空,后文有解釋
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//消息對列
mQueue = mLooper.mQueue;
//回調(diào)接口處理消息
mCallback = callback;
mAsynchronous = async;
}
- Looper.myLooper()做什么了
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
//為什么 sThreadLocal.get()返回不空捌苏薄胃榕?
//在哪里初始化了?
原來是ActivityThread 做了好事瞄摊!
在ActivityThread的main方法有這么一句
Looper.prepareMainLooper();
//讓我們看看實際做了什么
public static void prepareMainLooper() {
//在這里添加了loop
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");
}
//這里Q帧!换帜!同學(xué)楔壤,set一個新的對象
//所以就解釋了問題1 為什么不為空了。
//原來在ActivityThread里面創(chuàng)建一個mainLoop
sThreadLocal.set(new Looper(quitAllowed));
}
下面代碼驗證了 我們的在activity創(chuàng)建的handler使用loop的是mainLoop
boolean is=handler.getLooper().equals(Looper.getMainLooper());
//返回true 親測惯驼!
- 在ActivityThread#main方法還有一個重要操作
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();
//一個無盡的loop
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 {
//重點看這里分發(fā)消息了
//target是Handler實例
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();
}
}
handler.sendMessage(message); 做了什么递瑰?
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);
}
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 = 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;
}
總結(jié)
1.Message是消息的數(shù)據(jù)模型,可以存放各種消息议惰。
2.Loop 是一個永動機慎颗,不斷從消息隊列里讀出消息。
3.MessageQuene是一個消息隊列言询,不過是鏈表實現(xiàn)的數(shù)據(jù)結(jié)構(gòu)俯萎。
4.Handler是一個操作器,將消息傳入MessageQuene运杭,當(dāng)Loop讀出數(shù)據(jù)時讯屈,Handler的Callback回調(diào)處理消息。