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操作了,所以主线程中不需要额外的操作了。

     

  • 相关阅读:
    MFC加载图片
    动态数组类
    MFC程序打包方法
    如何在C++中使用动态三维数组
    Ansys热应力计算
    像使用数据库一样使用xml
    过年回家的一点感想
    前后端框架和设计模式
    国外支付PayPal
    可重用的管理后台代码
  • 原文地址:https://www.cnblogs.com/ljstudy/p/14590280.html
Copyright © 2011-2022 走看看