我有一个 AsyncTask 将图像上传到我的服务器。这部分工作正常,但我不知道如何处理中止过程。我有一个可以取消的 ProgressDialog,以及一个取消监听器。在这个监听器中,我中止了 http 请求和 AsyncTask ......但似乎这还不够,因为图像仍在上传。这是我的代码的样子:
public class UploadCubeThread extends AsyncTask<Cube, Void, String> {
private static final String url = "http://www.mywebsite.com/upload_cube.php";
private volatile HttpPost httppost = new HttpPost(url);
private ProgressDialog waitSpinner;
private Context context;
private HashMap<String, Integer> feedback;
private boolean success = false;
public UploadCubeThread(Context context) {
this.context = context;
this.feedback = new HashMap<String, Integer>();
waitSpinner = new ProgressDialog(context);
// Cancelable
waitSpinner.setCancelable(true);
waitSpinner.setCanceledOnTouchOutside(false);
waitSpinner.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
httppost.abort();
UploadCubeThread.this.cancel(true);
}
});
}
@Override
protected void onCancelled() {
super.onCancelled();
success = false;
feedback.put("cancelled", 0);
((UploadListener) context).onUploadComplete(success, feedback);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
waitSpinner.setMessage(context.getString(R.string.uploading));
waitSpinner.show();
}
@Override
protected String doInBackground(Cube... arg0) {
Cube cube = arg0[0];
String result = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compression
cube.getImage().compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
// Hash md5 pour l'intégrité
String hash = CubeUploader.encode(image_str);
nameValuePairs.add(new BasicNameValuePair("image", image_str));
nameValuePairs.add(new BasicNameValuePair("id_building", String
.valueOf(cube.getId_building())));
nameValuePairs.add(new BasicNameValuePair("title", cube.getTitle()));
nameValuePairs
.add(new BasicNameValuePair("content", cube.getContent()));
nameValuePairs.add(new BasicNameValuePair("hash", hash));
try {
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
// Utilisation de la réponse
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
} catch (UnknownHostException he) {
Log.e("CubeUpload", "Unknown Host : problem of connectivity ?");
result = "host_pb";
} catch (Exception e) {
Log.e("CubeUpload", "Error during upload: " + e.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Some process
((UploadListener) context).onUploadComplete(success, feedback);
waitSpinner.dismiss();
}
}
非常感谢您的帮助!