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

来源:互联网 发布:网络打印机添加xp 编辑:程序博客网 时间:2024/06/06 12:36

今天在子线程的handler里dismiss一个对话框,然后就报“Can't create handler inside thread that has not called Looper.prepare()”这个错。

他说“在没有调用Looper.prepare()之前,handler无法创建程序”

于是我就奇怪了 Looper是什么鬼。

参考以下博客:

http://blog.csdn.net/lmj623565791/article/details/38377229

http://blog.sina.com.cn/s/blog_78bb6d040101axl4.html

http://blog.csdn.net/hitlion2008/article/details/7561190


这才明白:

(1)一般在非 UI 的线程中不允许调弹出框,对话框之类的东东。

(2)Looper类别用来为一个线程开启一个消息循环。默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环),默认情况下Handler会与其被定义时所在线程的Looper绑定

(3)如果非主线程需要循环处理其他线程发来的消息,或者进行长期的复杂交互,则需要Looper建立消息队列。


解决方法:

 Loope.prepare(),初始化线程消息队列。

Looper.loop(),线程的消息队列开始运行,接收消息。

想要退出消息循环时,调用Looper.quit()注意,这个方法是要在对象(先调用Looper.myLooper()获取Looper对象)上面调用

简单的来说:用Looper.prepare()和Looper.loop()将你的代码包起来。


(4)强烈推荐我参考的第一条博文,很好地解释异步消息处理机制(Looper,Message,Handler)


阅读全文
0 0
原创粉丝点击