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

     

  • 相关阅读:
    Android中使用File文件进行数据存储
    Android 获取 json
    Android服务之Service
    php
    宝塔数据库连接不上
    idea中使用github
    elasticjob 当当的分布式定时任务管理
    定时任务规则生成器
    MySQL中group_concat()函数的排序方法
    mysql 中关于怎么写 row_number()over(order by) 类似的功能支持
  • 原文地址:https://www.cnblogs.com/ljstudy/p/14590280.html
Copyright © 2011-2022 走看看