Handler机制
1.在主线程中,创建一个Handler对象(你在哪里创建的handler就在那里接收)
2.子线程通过handler发送消息Message,调用sendMessage()方法将消息发送至MessagerQueue消息队列中
3.然后主线程中的Looper不断从消息从消息队列中取出消息对象,通过msg.target.dispatchMessage(msg)方法,将消息分发给对应的handler
4.主线程中dispagchMessage()方法中调用了handleMessage(),然后这方法在handler内部类重写,执行处理消息操作
(非主线程直接new一个handler会出现 Can't create handler inside thread that has not called Looper.prepare() 异常, 原因是非主线程没有 loop对象, 所以要调用 Looper.prepare() 方法 , 而且如果主线程给子线程发送消息,还要调用一个 Looper.loop() 的方法 ( 效果:无限从消息队列中取出消息 ) )
1.在主线程中,创建一个Handler对象(你在哪里创建的handler就在那里接收)
2.子线程通过handler发送消息Message,调用sendMessage()方法将消息发送至MessagerQueue消息队列中
3.然后主线程中的Looper不断从消息从消息队列中取出消息对象,通过msg.target.dispatchMessage(msg)方法,将消息分发给对应的handler
4.主线程中dispagchMessage()方法中调用了handleMessage(),然后这方法在handler内部类重写,执行处理消息操作
(非主线程直接new一个handler会出现 Can't create handler inside thread that has not called Looper.prepare() 异常, 原因是非主线程没有 loop对象, 所以要调用 Looper.prepare() 方法 , 而且如果主线程给子线程发送消息,还要调用一个 Looper.loop() 的方法 ( 效果:无限从消息队列中取出消息 ) )
class LoopT extends Thread {
@Override
public void run() {
super.run();
Looper.prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
Looper.loop();
Looper.loop();必须放在主线程的下面,因为他需要handler的handleMessage(Message msg)方法。