您的位置:首页 > 其它

handler——子线程中创建消息处理机制

2016-08-25 17:01 176 查看
转自http://blog.csdn.net/fdaopeng/article/details/7863840

Android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列(Message Queue)和一个消息循环(Looper)。Android中除了UI线程(主线程),创建的工作线程默认是没有消息循环和消息队列的。如果想让该线程具有消息队列和消息循环,并具有消息处理机制,就需要在线程中首先调用Looper.prepare()来创建消息队列,然后调用Looper.loop()进入消息循环。

class LooperThread extends Thread {
public Handler mHandler;

public void run() {
Looper.prepare();

mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};

Looper.loop();
}
}

 这样该线程就具有了消息处理机制了。如果不调用Looper.prepare()来创建消息队列,会报"Java.lang.RuntimeException: Can't create handler inside thread
that has not called Looper.prepare()"的错误。
在子线程的run()方法里调用Looper.prepare(),实例化一个Handler对象,调用Looper.loop()使线程进入消息循环

Handler对象的实例话必须在Looper.prepare()之后。当我们要给具有消息循环的线程发送消息时,我们先要获得具有消息循环的线程的 Handler 对象(或者先获取具有消息循环的线程的Looper对象,再使用这个Looper对象构造Handler对象),构造一个Message对象,然后调用Handler对象的sendMessage方法

Message message=Message.obtain();
message.what=1;
message.arg1=count;
handler.sendMessage(message);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐