我想在活动中通过AsyncTask使用Android MultiPart Entity上传多个图像文件。当我尝试上传单个图像文件时,进度对话框显示正确的进度,一旦达到100%的进度,对话框就会解除并执行其他任务。但是,当我尝试上传多个图像文件时,它显示100%的进度,并且进度对话框一直停留,直到其他图像文件上传到服务器。我使用for循环将多个图像文件添加到实体。但是当我试图获得内容长度时,我似乎得到了错误的价值。
@SuppressWarnings("deprecation")
private class UploadAttachments extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
long totalSize = 0;
int statusCode;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage(getString(R.string.label_upload_attachments));
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMax(mFilePaths.size());
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Network.URL_UPLOAD);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
for (int i = 0; i < mFilePaths.size(); i++) {
entity.addPart("image" + i, new FileBody(new File(mFilePaths.get(i))));
mPrefix += 1;
entity.addPart("prefix" + i, new StringBody(String.valueOf(mPrefix)));
}
totalSize = entity.getContentLength();
entity.addPart("count", new StringBody(String.valueOf(mFilePaths.size())));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = getString(R.string.label_upload_successful);
} else {
responseString = getString(R.string.error_network_error);
}
} catch (IOException e) {
responseString = getString(R.string.error_network_error);
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (mToast != null) mToast.cancel();
mToast = makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
mToast.show();
mPreferences.clearRegDetails();
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
}
请看一下。请帮帮我!感谢。