当下载文件我向用户显示此对话框时,有取消按钮
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading ..");
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
我的下载代码是:
protected String doInBackground(String... aurl) {
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(sunDir.getPath()
+ musicFileName);
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;
}
答案 0 :(得分:3)
按下对话文件下载时取消按钮不取消
您需要使用AsyncTask.cancel()取消取消按钮上的AsyncTask,因为:
public static boolean downloadstatus=true;
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
your_AsyncTask.cancel(true); //<<<<<
downloadstatus=false;
dialog.cancel();
}
});
我想当用户按下取消按钮,如果文件下载完成或 不能完全删除文件
您需要检查在doInBackground
内运行或取消AsyncTask以停止文件下载:
while ((count = input.read(data)) != -1) {
if(!your_AsyncTask.isCancelled() && downloadstatus !=false){
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
else{
// free all resources here
break;
}
}