先看个直观的上层调用的例子:
定义一个线程, 在里面定义jrdHandler
private void ThreadLoopUse(){
new Thread(new Runnable() {
@Override
public void run() {
//Looper循环
Looper.prepare();
//中间循环接收处理
jrdHandler = new android.os.Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == 0x01){
//从别的线程发送0x01的消息过来,
jrdMainHadler.sendEmptyMessage(0x01);
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
jrdMainHadler.sendEmptyMessage(0x02);
}
}
};
Looper.loop();
}
}).start();
}
主线程通过jrdHandler来向子线程发送消息
jrdHandler.sendEmptyMessage(0x01);
下面来分解一下Looper, Handler, MessageQueue:
Looper类: 用于封装消息循环
Handler类: 封装消息的投递,处理
针对示例,主要分析Looper.prepare(),Looper.loop(), Handler.sendMessage();
Looper.Prepare
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));
}
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
在来看看Looper的构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在构造函数里面复制了一个messageQueue和mThread;这样Looper就和Thread绑定在一起了;
下面看看Looper的loop函数
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
try {
msg.target.dispatchMessage(msg);//msg.target是一个Handler
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
}
}
Looper, Message和Handler的关系:
a. Looper中有一个MessageQueue,一个个处理Message;
b. Mesage中有一个Handler,这个Handler来处理message;
c. Handler负责发送和处理消息, 它调用当前线程的 Loop而