2 Java 代码
16
public Handler(){ mLooper = Looper.myLooper(); // 取得当前线程的 Looper,如果抛
异常
17
if (mLooper == null) { throw new RuntimeException(
18
"Can't create handler inside thread that has not called Looper.prepare()"); }
19
mQueue = mLooper.mQueue; // 取得消息队列 mCallback = null;
20
}
3 Java 代码
21
//不管调用哪个方法,最终执行的是
22
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
23
boolean sent = false;
24
// 取得消息队列
25
MessageQueue queue = mQueue;
26
if (queue != null) {
27
msg.target = this; // 消息发出着是自己
28
sent = queue.enqueueMessage(msg, uptimeMillis); // 添加到消息队列中
29
}
30
else {
31
RuntimeException e = new RuntimeException(
32
this + " sendMessageAtTime() called with no mQueue");
33
Log.w("Looper", e.getMessage(), e);
34
}
35
return sent;
36
}
37
final boolean enqueueMessage(Message msg, long when) {
38
if (msg.when != 0) {
39
throw new AndroidRuntimeException(msg
40
+ " This message is already in use.");
41
}
42
if (msg.target == null && !mQuitAllowed) {
43
throw new RuntimeException("Main thread not allowed to quit");
44
}
45
synchronized (this) {
46
if (mQuiting) {
47
RuntimeException e = new RuntimeException(
48
msg.target + " sending message to a Handler on a dead thread");
49
Log.w("MessageQueue", e.getMessage(), e);
50
return false;
51
} else if (msg.target == null) {
52
mQuiting = true;
53
}