zoukankan      html  css  js  c++  java
  • Can't create handler inside thread that has not called Looper.prepare()

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

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

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

  • 相关阅读:
    mysql-5.7.16-linux-glibc2.5-x86_64精简后的主从配置
    solr安装
    ffmpeg安装
    saltstack之keepalived的安装配置
    saltstack之haproxy的安装配置
    saltstack1
    logstash运输器以及kibana的更多操作
    logstash编写2以及结合kibana使用
    logstash5.x安装及简单运用
    ELK之elasticsearch5.6的安装和head插件的安装
  • 原文地址:https://www.cnblogs.com/sonicit/p/2858475.html
Copyright © 2011-2022 走看看