在下面的代码中,如果下载被取消(例如,按下或关闭应用程序),我希望不保存不完整的文件并将其删除。
我该怎么做?
这是我的代码的一部分:
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);
}
}
答案 0 :(得分:3)
请注意,如果一切正常,则当用户按下后退按钮时,AsyncTask 不会被取消。如果我没记错的话,如果活动被销毁,它也不会自动取消,但只有在任务上调用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
}
答案 1 :(得分:0)
您可以添加isCanceled
标记,每次写入文件时都会检查该标记:
while ((count = input.read(data)) != -1 && isCanceled)
另外添加:
catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
finaly{
if(isCanceled)
{
// delete file code here
}
}
当您需要/需要取消时,您将此标志设置为true。
答案 2 :(得分:0)
设置全局布尔标志boolean downloadComplete = false;
并在onPostExecute中将其更改为downloadComplete = true;
and override
onDestroy()method.
then check flag in
onDestroy()`文件是否下载
if(!downloadComplete)
{
//then delete file
}
当您取消下载时,将不会调用onPostExecute(),因此您的标记值仍为false
答案 3 :(得分:0)
写下面的代码
@Override
public void onBackPressed() {
super.onBackPressed();
if(DownloadFileFromURL!=null){
if(DownloadFileFromURL.getStatus()==Status.RUNNING||DownloadFileFromURL.getStatus()==Status.PENDING){
DownloadFileFromURL.cancel(true);
DownloadFileFromURL=null;
File file= new File("/sdcard/EBKH/samat.mp3");
file.delete();
}
}
}