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();
}
}
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();
}