读书人

Can#039;t create handler inside thread

发布时间: 2012-06-29 15:48:46 作者: rapoo

Can't create handler inside thread that has not called Looper.prepare() 异常问题

产生该问题原因:

? ? ? ?1. 在线程中调用handler的sendMessage方法

? ? ? ?2。AsyncTask中的doInBackground方法不可直接操作UI

解决方法:

? ? ? 在调用handler的方法前执行Looper.prepare()。Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用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();}
??

因为activity的主线程是自己创建消息队列的,所以在Activity中新建Handler时,不需要先调用Looper.prepare()。

读书人网 >移动开发

热点推荐