handler流程源码分析
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对象,并于当前线程进行绑定,set进ThreadLocal中
}
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.recycleUnchecked();
}
}
app启动后调用Lopper类中的looper方法
通过MyLooper()创建当前线程(app启动时默认主线程,以后是Looper对象所在线程)的looper对象
创建MessageQueue对象,与Looper类中MessageQueue成员变量共享同一内存空间,me.mQueue被改变时,MessageQueue对象随之改变
创建死循环,不断的从MessageQueue队列中取出message对象,为空则阻塞
通过msg.target.dispatchMessage(msg)进行消息的分发,调用该msg所在handler对象的handleMessage方法(target在message入队时已被赋值:Handler类的enqueueMessage()方法中完成target赋值)
整个过程都是在主线程中完成的,所以说子线程如果要创建自己的Looper对象,则需要在自线程中调用loop()方法
子线程给主线程及子线程给子线程传递数据
Handler中传入的Looper与哪个线程进行绑定,消息就传入哪个线程中进行处理
eg:
Looper.getMainLooper()获得的Looper对象与主线程进行绑定,可以在子线程中sendMessage,handlerMessage()所处线程是主线程
Looper.prepare()获得与当前线程绑定的Looper对象,
如果是在主线程中,则与Looper.getMainLooper()一致。
如果是在子线程中,则是与子线程进行通信(子与子通信),最后还需调用Looper.loop()进行创建该线程的Looper对象。
Looper.myLooper()可以获得该Looper对象。如果直不执行Looper.prepare()而直接执行Looper.myLooper()则会空指针异常。
Looper不断获取MessageQueue中的一个Message,然后由Handler来处理。
中央处理器(Looper)从内存(MessageQueue)中取出指令(Message),执行指令(Handler).
一.每个Thread只对应一个Looper
二.每个Looper只对应一个MessageQueue
三.每个MessageQueue中对应n个Message
四.每个Message最多可以
每个Message中最多指定一个Handler来处理事件

浙公网安备 33010602011771号