Handler机制理解了又给忘了,这次直接用主要的代码执行步骤来理解(抓住脉络,细节代码全部忽略):
程序启动,会在ActivityThread的main()方法里调用两个方法:
//初始化Looper
Looper.prepareMainLooper(){
Looper.prepare(){
sThreadLocal.set(new Looper(quitAllowed))
};
sMainLooper = myLooper(){ sThreadLocal.get(); }
}
//开始循环从消息队列取消息
Looper.loop(){
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// 没有任务后退出循环
return;
}
msg.target.dispatchMessage(msg);
}
然后在主线程(其他线程也一样,就是初始化Looper的线程,这里已主线程为例)中:
new Handler(){
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can‘t create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
}
之后可以在任何线程持有Handler的引用,调用下面的方法(为了简单理解就直接把方法嵌套这么奇怪的写了,也省略了一些参数)
Handler.sendMessage(){
enqueueMessage(){
msg.target = Handler.this;
queue.enqueueMessage(msg, uptimeMillis){
needWake = true;//是否启动Looper.loop()循环
Message p = mMessages;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
}
if (needWake) {
nativeWake(mPtr);//通过nativeWake方法唤醒Looper.loop()循环
}
}
}
}
而唤醒Looper.loop()循环后,当循环到当前任务时,就
msg.target.dispatchMessage(Message msg) {
handleMessage(msg);//回调主线程中实现的方法
}
原文:http://www.cnblogs.com/huangtianfu/p/4986948.html