`
Faroe
  • 浏览: 9215 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

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()。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics