可以通过handler将message和runnable对象发送到该handler所关联线程的messagequeue中,然后该消息队列一直在循环拿出一个message,并对其处理。
当创建handler时,该handler就绑定了当前创建handler的线程。
一.在子线程使用Handler方式为:
Runnable runnable = new Runnable(){
public void run(){
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
};
我们来分析一下,为什么要这么使用:
1. Looper.prepare();我们看看源码是怎么实现的;
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,并且和当前线程绑定,也就是实例化一个Looper绑定到当前子线程。
2.Handler handler = new Handler();
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;
}
这一段是实例化Handler。
3. 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();
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
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.recycle();
}
}
我们可以发现for(;;)的死循环,queue.next()从MessageQueue队列中取消息,
msg.target.dispatchMessage(msg); 其中msg.target一般是handler(下文会提到),然后由handler来分发消息。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这里我看看到了熟悉的代码handleMessage();先不看msg.callback和mCallback
当我们实例化handler,重写handleMessage(),会在handlerMessage里面处理自己的逻辑(比如更新Ui等)
二:下面我们看看在UI线程使用handler的方式
Handler handler = new Handler();
handler.sendMessage();
这里有一个问题:为什么UI线程没有调用 Looper.prepare()和Looper.loop();
带着这个问题,我们来看看UI线程的源码;
下面是ActivityThread的主函数入口:
public static void main(String[] args) {
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());
Security.addProvider(new AndroidKeyStoreProvider());
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");
}
我们可以看到主线程已经创建了Looper,因此,在主线程使用handler时不需要Looper.prepare();
三 new Handler(Looper.getMainLooper()) 这种情况是,使用主线程的Looper
比如在子线程里面初始化handler,需要更新ui,那么就可以这么用。