我尝试将文件加载到服务器。我需要等待所有操作完成后才能启动enother方法。所以我用同步通话。我尝试在启动新线程之前显示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线程上运行,因此您可以在此处轻松关闭它。