我有一个从服务器下载文件的应用程序。下载在 Asynctask 中。我有一个显示下载进度的进度条。如果文件需要太长时间才能完成下载,我会提出取消请求。这只是关闭进度对话框,当再次单击文件时,它不会重新开始下载。我该如何处理这种情况。很多研究让我很困惑......我认为它就像下载显示下载进度 - > OnCancel,终止下载一样简单(不幸的是我找不到杀死Asynctask的方法) - > 点击文件,重新开始下载.....但是,唉,我似乎没有办法......请帮助......
这是我所做的事情的来源......
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(DIALOG_DOWNLOAD_PROGRESS);//to test i commented
mProgressDialog = new ProgressDialog(Shelf_books.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
/*mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
mytask.cancel(true);
}
});*/
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
mytask.cancel(true);
}
});
mProgressDialog.show();
}
protected void onProgressUpdate(String... progress) {
Log.d("kunal",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected void onCancelled() {
Log.d("kunal","cancel method");
running = false;
}
@Override
protected String doInBackground(String... arg1) {
// TODO Auto-generated method stub
int count;
if(isCancelled()==false)//test
{//test
try{
URL url = new URL(arg1[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("kunal", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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) {
Log.d("kunal","exception occured");
}
}//test
return null;
}
}
/*creating async class ends here*/
}
下面是 onExecute 的调用,这是在单击按钮时调用的......
public void DownloadFile(String fileURL, File directory) {
/*testing my code here starts */
try {
URL u = new URL(fileURL);
new DownloadFileAsync().execute(fileURL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}