需要先调用Looper.prepare(),为什么呢,看Handler的构造函数中,调用Looper.myLooper()获取mLooper,如果为空则会报这个错误,
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;
}
再看Looper的myLooper()方法,是通过sThreadLocal.get()方法来获取,
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
然后再来看看Looper.prepare()里面,就是给sThreadLocal设置一个Looper对象
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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
那为什么在主线程中不需要调用Looper.prepare()呢,因为在程序启动时,系统已经在ActivityThread的main方法中调用了Looper.prepareMainLooper(),这个方法又会调用Looper.prepare()方法
public static void main(String[] args) {
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
EventLogger.setReporter(new EventLoggingReporter());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
发送消息的流程
Handler中的发送消息方法,大多最后都会调用sendMessageAtTime()方法,然后再调用MessageQueue的enqueueMessage方法,而MessageQueue是什么呢?就是一个存消息的队列,而enqueueMessage就是入队方法,
在enqueueMessage方法中,就是把消息按时间顺序插入队列中,而Handler的sendMessageAtFrontOfQueue方法也是调用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;
}
那消息的出队呢?在Looper.loop()方法中,会进入一个死循环,并不断调用MessageQueue的next方法,它的逻辑就是让下一条消息成为mMessages,否则进入阻塞状态,等待新消息入队。
而在loop方法中,每当有一个消息出队,就将它传递到msg.target的dispatchMessage方法中,而msg.target也就是Handler,Handler的dispatchMessage方法的逻辑就是调用handleCallback、mCallBack或自身的handleMessage方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
除了发消息来更新UI,还有这些方法可以在子线程中更新UI
- Handler的post()方法
- View的post()方法
- Activity的runOnUiThread()方法
Handler的post方法就是调用sendMessageDelayed方法,而消息则是通过getPostMessage把Runnable转换成一条信息,并将Runnable对象赋值给msg.callback,
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
而在Handler的dispatchMessage方法中会检查msg.callback是否为空,如果不为空则会调用handleCallback方法,也就是调用Runnable的run方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
View中的post方法也是调用Handler中的post方法
public boolean post(Runnable action) {
Handler handler;
if (mAttachInfo != null) {
handler = mAttachInfo.mHandler;
} else {
ViewRoot.getRunQueue().post(action);
return true;
}
return handler.post(action);
}
Activity的runOnUiThread则是先判断是否在UI线程,如果是,直接运行run方法;否则也是调用Handler的post方法。
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}