【发布时间】:2018-11-05 13:49:03
【问题描述】:
我正在使用 AsyncTask 下载文件。它还显示一个进度对话框并有一个取消按钮,当我单击取消时,它应该会阻止 AsyncTask 进一步下载,但它什么也没做。
取消按钮代码:
new DownloadFileAsync().cancel(true);
异步任务:
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
if (!isCancelled()) {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File FileDirectory = new File(dir, guessed_file_name);
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(FileDirectory);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
Toast.makeText(getBaseContext(), "download completed!", Toast.LENGTH_LONG).show();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
finish();
}
}
}
【问题讨论】: