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

1、Handler不带参数的默认构造函数:newHandler(),实际上是通过Looper.myLooper()来获取当前线程中的消息循环,

     而默认情况下,线程是没有消息循环的,所以要调用Looper.prepare()来给线程创建消息循环,然后再通 过,Looper.loop()来使消息循环起作用(run方法体内的开始和结束添加)

     另外,Activity的MainUI线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。

2、主线程向子线程发送数据列子

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

复制代码
1         this.mThirdHandler = new Handler(){
2             @Override
3             public void handleMessage(android.os.Message msg) {
4                 super.handleMessage(msg);
5                 Bundle bundle = msg.getData();
6                 isStop = bundle.getBoolean(mContext.getText(R.string.str_message_stop).toString());//isStop为基类中的一个私有成员
7             };
8         };
复制代码

但不知道为啥一直报错: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,实例化基类时引入的一个参数。

希望以上的方法,可以给大家带来点帮助。



作用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值