zoukankan      html  css  js  c++  java
  • Android学习记录---在子线程中使用组件ui会报错

    在子线程中使用组件ui会报错?

    例如:

    //4、发起请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("login", e.getMessage());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String s = response.body().string();
                    Log.e("login", s);
                    //在子线程中使用组件ui会报错
                    Toast.makeText(LoginActivity.this,"",Toast.LENGTH_LONG).show();;
                }
            });
    

     第一种解决方法:

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String s = response.body().string();
                    Log.e("login", s);
                    //在子线程中使用组件ui会报错
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this,"",Toast.LENGTH_LONG).show();;
                        }
                    });
                    Toast.makeText(LoginActivity.this,"",Toast.LENGTH_LONG).show();;
                }

    第二种解决方法:

      @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String s = response.body().string();
                    Log.e("login", s);
                    //在子线程中使用组件ui会报错
                    Looper.prepare();
                    Toast.makeText(LoginActivity.this,"",Toast.LENGTH_LONG).show();;
                    Looper.loop();
                }

    总结:为啥在主线程中使用组件不会报错,因为主线程中父类已经帮我们做了Looper操作了,所以主线程中不需要额外的操作了。

     

  • 相关阅读:
    html5shiv.js-让IE浏览器支持HTML5标准
    CSS2系列:外边距合并问题(margincollapse)
    HTML5:离线存储(缓存机制)-IndexDB
    CSS3系列:流式(弹性)布局(flex布局)
    Sublime Text 3 常用插件以及安装方法(转)
    后台配置参数写在文件上
    20160414
    2016413
    20160412
    网页设计素材网站
  • 原文地址:https://www.cnblogs.com/ljstudy/p/14590280.html
Copyright © 2011-2022 走看看