gpt4 book ai didi

android - ProgressDialog 不会在新线程之前启动

转载 作者:行者123 更新时间:2023-11-30 00:51:14 25 4
gpt4 key购买 nike

我尝试将文件加载到服务器。我需要等待所有操作完成才能启动另一种方法。所以我使用同步调用。我尝试在开始新线程之前显示 ProgressDialog,但是,虽然所有线程都没有完成,但我的 UI 线程只是卡住了。

private void uploadImageSync() {
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(BarcodActivity.this);
progressDialog.setMessage("Load...");
progressDialog.show();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface service = retrofit.create(RequestInterface.class);

int i=0;
while (i++ <= 4) {
File f = getOutputMediaFilePath(mCode + "_"+i, true);
if(f.exists()){
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f);

MultipartBody.Part body = MultipartBody.Part.createFormData("file", f.getName(), requestFile);

final Call<ResponseBody> resultCall = service.uploadImage(body);

Thread t = new Thread(new Runnable() {
public void run() {
try {
resultCall.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
}});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
progressDialog.dismiss();
}

最佳答案

您的 UI 线程卡住的原因是因为您正在调用 t.join()。您的 UI Thread 会等待新的 Thread 完成。

相反,您可以使用 AsyncTask,因为该类是为此类任务而创建的。

这是一个关于如何使用它和 android dev guide 的一般示例

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}

protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}

new DownloadFilesTask().execute(url1, url2, url3);

请注意,onPostExecute 在 UI 线程上运行,因此您可以轻松地将其关闭。

关于android - ProgressDialog 不会在新线程之前启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995079/

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