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

 

原文地址:https://www.cnblogs.com/ljstudy/p/14590280.html