在okhttp的callback回调中加Toast出现Cant create handler inside hread that has not called Looper.prepare()

在okhttp的callback回调中加Toast出现Cant create handler inside hread that has not called Looper.prepare()

分析:callback中回调的response方法中还是在子线程中运行的,所以要调取Toast必须回到主线程中更新ui

解决方法:在调用Toast(或者AlertDialog)的地方的前面加上Looper.prepare(),后边加上Looper.loop()即可解决问题;也就是说用Looper.prepare()和Looper.loop()把Toast前后包起来。

prepare方法是在子线程中new Looper,把Toast放进了队列之中,loop方法就会进入无限循环取值。

还一个方法就是开启一个onUiThread 或者异步消息handle 或者asyncTask


```java
 OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(path)
                .get()//可以不写。默认get
                .build();
        Call call = okHttpClient.newCall(request);//调用已经准备好的
//        开启异步线程访问网络
        call.enqueue(new Callback() {
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
                Looper.prepare();
                if (weatherBean.getError_code()==0) {
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("city",city);
                    startActivity(intent);
                    Message msg = new Message();
                    msg.what = MSG_OK;
                    msg.obj = result;
                    handler.sendMessage(msg);
        }else{
                    Toast.makeText(getApplicationContext(),"暂时未收入此城市天气信息...",Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
        });

posted @ 2019-12-27 23:14  榆阳123  阅读(85)  评论(0)    收藏  举报