温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题

发布时间:2021-10-21 10:46:21 来源:亿速云 阅读:797 作者:小新 栏目:移动开发

这篇文章主要介绍了如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

    在android开发中,主线程不能进行耗时操作,所以我们经常把耗时操作放在子线程中进行,那么就需要子线程与主线程相互交流,就需要使用到handler.

    而在使用handler过程中,如果对handler使用不太熟练的话就偶尔会出现Can't create handler inside thread that has not called Looper.prepare()的报错异常。之前在Handler的原理的博文中有讲到,Handler的使用会依靠Looper循环来发送消息,如果不创建Looper对象,消息就无法发送,系统就会崩溃。那么为什么使用handler有时候可以运行,有时候不能运行呢?

    其实就是如果在主线程中创建handler时,系统会自动创建Looper,但是在子线程中创建handler时,是不会自动创建Looper的,此时如果不手动创建Looper,系统就会崩溃

    举例如下:首先在子线程创建Handler(即主线程发送消息给子线程处理)

    如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题

如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题

系统就会报出Can't create handler inside thread that has not called Looper.prepare()的报错异常。

解决方法是:

如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题

通过Looper.prepare();创建Looper对象

    下面在主线程中创建Handler

如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题

在主线程创建Handler(即子线程发送消息给主线程处理),系统就会自动创建Looper,而不需要手动创建Looper.

感谢你能够认真阅读完这篇文章,希望小编分享的“如何解决使用Handler时Can't create handler inside thread that has not called Looper.prepare()问题”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI