我的应用程序中有一个带有处理对话框的 AsyncTask 。我在关闭对话框时取消后台任务,但它没有取消任务但对话框消失。这是代码
DownloadImageTask dm = null;//new DownloadImageTask();
dm = new DownloadImageTask();
dm.execute();
预执行:
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Tab_book.this);
pd.setTitle("Loading Images..");
pd.setMessage("Please wait...");
pd.setCancelable(true);
pd.show();
pd.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
dm.cancel(true);
//finish();
}
});
}
取消方法:
protected void onCancelled() {
cancel(true);
}
做背景:
protected Bitmap doInBackground(Void... params) {
int j = 0;// List.size();
try {
for (; j < List.size(); j++) {
reviewImageLink = List.get(j).get(TAG_Image);
URL url = new URL(reviewImageLink);
// URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1,reviewImageLink.length());
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(),getResources().getString(R.string.directory_book));
// if(!sdImageMainDirectory.exists()){
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");
}
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length
- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
setProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
saveToSDCard(bitmap, name);
}//
images();
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
finally{
Log.v("tag", "try again ");
}
// }
// Bitmap b=images.get(j);
return null;
//}
}