在下面的代码中,如果下载被取消(例如,按返回或关闭应用程序),我希望不要保存不完整的文件并将其删除。
我该怎么做?
这是我的部分代码:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/samat.mp3");
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.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}
最佳答案
请注意,如果一切正常,AsyncTask 不会在用户按下后退按钮时取消。如果我没记错的话,如果 Activity 被销毁,它也不会自动取消,但只有在任务上调用 cancel()
时才会取消。
如果你想在调用取消时删除你的文件,请不要添加不必要的逻辑,只需重写AsyncTask.onCancelled()
即可。 :
@Override
protected void onCancelled(Object Result) {
// If the background task was cancelled, delete the mp3
File file= new File("/sdcard/EBKH/samat.mp3");
file.delete();
}
@Override
protected void onCancelled() {
// Implement this one if you also support API levels lower than 11
}
关于android - 如果下载被取消,不保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014237/