gpt4 book ai didi

Android okhttp 异步进度对话框

转载 作者:行者123 更新时间:2023-11-29 17:24:16 25 4
gpt4 key购买 nike

我想把progressdialog加入到okhttp中(异步的,不是AsyncTask)

但是我得到了这个错误:

Error: Can't create handler inside thread that has not called 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");
}

}

});

最佳答案

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
}
});
}

关于Android okhttp 异步进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35253329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com