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

     

  • 相关阅读:
    PHP中关于字符串的连接
    好用的FireFox(FF)插件
    Scripted Operation
    Scripted device
    chgrp chown
    wait_for_devices
    mysql create user
    mysql
    create user mysql
    Inserting/Removing shutters and filters
  • 原文地址:https://www.cnblogs.com/ljstudy/p/14590280.html
Copyright © 2011-2022 走看看