博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Can't create handler inside thread that has not called Looper.prepare()
阅读量:2191 次
发布时间:2019-05-02

本文共 1074 字,大约阅读时间需要 3 分钟。

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

在一个基类中,创建一个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,实例化基类时引入的一个参数。

转载地址:http://ywdub.baihongyu.com/

你可能感兴趣的文章
用 LSTM 来做一个分类小问题
查看>>
详解 LSTM
查看>>
按时间轴简述九大卷积神经网络
查看>>
详解循环神经网络(Recurrent Neural Network)
查看>>
为什么要用交叉验证
查看>>
用学习曲线 learning curve 来判别过拟合问题
查看>>
用验证曲线 validation curve 选择超参数
查看>>
用 Grid Search 对 SVM 进行调参
查看>>
用 Pipeline 将训练集参数重复应用到测试集
查看>>
PCA 的数学原理和可视化效果
查看>>
机器学习中常用评估指标汇总
查看>>
什么是 ROC AUC
查看>>
Bagging 简述
查看>>
详解 Stacking 的 python 实现
查看>>
简述极大似然估计
查看>>
用线性判别分析 LDA 降维
查看>>
用 Doc2Vec 得到文档/段落/句子的向量表达
查看>>
使聊天机器人具有个性
查看>>
使聊天机器人的对话更有营养
查看>>
一个 tflearn 情感分析小例子
查看>>