0、前言
android handler机制的四个组成部分:Handler、Message、MessageQueue、Looper。
1、四者作用与关系
**Mesage(消息)**是相同或不同的线程相互作用的媒介,对应着一个操作。
Looper(循环者)是创建handler的必备条件,主要用于创建当前线程的MessageQueue(消息队列)实例(一个Looper一一对应一个线程Thread额,二者之间不存在一对多的关系),然后进入一个无限循环体不断从该MessageQueue中读取消息。常用方法就是prepare()和loop(),注意看下方法上面的英文注释额:
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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 (;;) {
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;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
消息队列MessageQueue主要包含两个操作:插入和读取。读操作伴随着删除操作,插入和删除对应的方法分别为enqueueMessage和next()。
enqueueMessage的作用是插入一条消息,从代码可以看出MessageQueue虽然叫消息队列,实际上内部实现是单链表的数据结构,这是由于单链表在插入和删除方便比较有优势。
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;
}
next的作用是从消息队列中取出消息并将其从消息队列中移除,next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法将会一直堵塞在这里。当有新消息到来时,next方法就会返回这条消息并将该消息从链表中删除。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
Handler是传递和处理消息的工具,Handler可以将Message插入到MessageQueue(消息队列)的队列尾,同时处理MessageQueue队列头的Message。handler可以通过如下7种方式发送消息,这7个方法绕来绕去,其实最终调用的是sendMessageAtTime方法将此Message插入都消息队列尾部。
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}
handler处理消息的方法如下,其实和View事件处理机制有点相似,如果Message本身有callback,则直接交给Message的callback处理,如果本Handler设置了mCallback,则交给mCallback处理,最后没人认领了则去执行handleMessage方法,一般我们都是直接重写handleMessage方法。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg); //如果Message本身有callback,则直接交给Message的callback处理
} else {
//如果本Handler设置了mCallback,则交给mCallback处理
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
2、子线程可以更新UI的疑惑
android规定只有主线程才可以操作UI,而那些耗时的操作交给子线程去处理,处理完了就发个Message给主线程,主线程再更新UI。如上面所提,Looper是Handler创建的必要条件,平时咱们使用的Acticity中之所以没有看到prepare()和loop()两方法,是由于google在ActivityThread中已经帮我们封装好了(如下)。
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
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");
}
那我现在在子线程中创建一个SubLooper和SubHandler,那此时这个SubLooper和SubHandler应该属于子线程的吧,然后在通过这个SubHandler在主线程发送Message到子线程,子线程再处理此Message去更新UI,dialog和toast确实弹出来了。这不就推翻了子线程不能更新UI的命题吗?难道说所有的Handler都属于主线程??
new Thread(new Runnable() {
public void run() {
Handler handlerMain = new Handler(Looper.getMainLooper()) { //注意这里使用Looper.getMainLooper()获取的是主线程的Looper
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 2:
Toast.makeText(getApplicationContext(),"主线程的Handler处理来自主线程的消息"+Process.myTid(),Toast.LENGTH_SHORT).show();
break;
default:
break;
}
Log.d(TAG, "handleMainMessageInner: " + Process.myTid()); //此时打印主线程的id
}
};
Looper.prepare();
looperSub = Looper.myLooper();
handlerSub = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 2:
Toast.makeText(getApplicationContext(), "子线程处理来自主线程的消息" + Process.myTid(), Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("hha")
.setMessage("zzzzzzz")
.show();
break;
default:
break;
}
Log.d(TAG, "handleMessage: " + Process.myTid()); //此时打印子线程的id
}
};
handlerSub.sendEmptyMessage(1);
handlerMain.sendEmptyMessage(1);
Looper.loop();
}
}).start();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
new Thread(new Runnable() {
@Override
public void run() {
m_handler.sendEmptyMessage(1);
}
}).start();
break;
case R.id.btn2:
handlerSub.sendEmptyMessage(2);
break;
default:
break;
}
}
总结:
子线程操作UI报异常是由于下面代码检查线程不一致导致的
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
那么通过Looper.prepare()和 Looper.loop()就可以来创建和循环处理消息,消息的创建和处理在同一个线程就不怕线程不一致的问题了。
参考源码