您现在的位置是:首页 > 文章详情

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

日期:2016-08-08点击:511
版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/52163029

最近做项目时出现个问题。

在一个基类中,创建一个Handler对象用于主线程向子线程发送数据,代码如下:

this.mThirdHandler = new Handler(){ @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); isStop = bundle.getBoolean(mContext.getText(R.string.str_message_stop).toString());//isStop为基类中的一个私有成员 }; };

但不知道为啥一直报错:Can't create handler inside thread that has not called Looper.prepare()。

搜索后发现,原因是此Handler没有Looper。到哪儿去找Looper呢?自己建?

在代码前加入Looper.prepare();,心想这回可以了吧?

没想到依然报错,错误显示,一个主进程只能有一个Looper,要死了。郁闷中...

突然我想到主进程中肯定有Looper,Context.getMainLooper(),再看Handler的实例化时是可以指定Looper的,太爽了,最后代码如下

this.mThirdHandler = new Handler(mContext.getMainLooper()){ @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); isStop = bundle.getBoolean(mContext.getText(R.string.str_message_stop).toString()); }; };

mContext为主界面context,实例化基类时引入的一个参数。
原文链接:https://yq.aliyun.com/articles/631588
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章