【问题标题】:Android okhttp Async progressdialogAndroid okhttp 异步进度对话框
【发布时间】:2016-05-17 03:39:46
【问题描述】:

我想在okhttp中添加progressdialog(异步,不是AsyncTask)

但我收到了这个错误:

错误:无法在未调用的线程内创建处理程序 Looper.prepare()

如何以适当的方式修复它?我想确定这是最好的方法。

  client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("TAG_response", " brak neta lub polaczenia z serwerem ");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
                 progress = ProgressDialog.show(SignUp.this, "dialog title",
                    "dialog message", true);
            try {
                Log.d("TAGx", response.body().string());
                if (response.isSuccessful()) {
                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                        //System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                        Log.d("TAG2", responseHeaders.name(i));
                        Log.d("TAG3", responseHeaders.value(i));

                    }
                    Log.d("TAG", response.body().string());
                    progress.dismiss();
                    main_activity();
                }
                else{
                    progress.dismiss();

                    alertUserAboutError();
                }
            }
            catch (IOException e){
                Log.d("TAG", "error");
            }

        }

    });

【问题讨论】:

  • 您应该在将请求排入队列并在 onFailure 和 onResponse 中关闭之前移动显示对话框的代码。

标签: android asynchronous progressdialog okhttp okhttp3


【解决方案1】:

OkHttp 在执行 http 调用的同一后台线程上运行 onResponse 方法。因为您正在进行异步调用,这意味着它不会是 Android 主线程。

要从 onResponse 在主线程上运行代码,您可以使用 Handler 和 Runnable:

client.newCall(request).enqueue(new Callback() {

    Handler handler = new Handler(SignUp.this.getMainLooper());

    @Override
    public void onFailure(Call call, IOException e) {
        //...
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {

        handler.post(new Runnable() {
            @Override
            public void run() {

                // whatever you want to do on the main thread
            }
        });
    }

【讨论】:

    猜你喜欢
    • 2011-07-29
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多