1

In the following code I want don't save incomplete file and delete it, if download was cancelled (e.g. press back or close app).

How can I do it?

This is part of my code:

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);
    }
}
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
user3325172
  • 47
  • 1
  • 6

4 Answers4

3

Note that, if all is well, an AsyncTask does not get cancelled when a user presses a back button. If I remember correctly, it also does not get cancelled automatically if the activity is destroyed, but only gets cancelled when cancel() is called on the task.

If you want to delete your file if the cancel was called, please don't add unnecessary logic, just override 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
}
Menno
  • 1,133
  • 9
  • 14
0

You could add a isCanceled flag that you will check every time you write to the file :

while ((count = input.read(data)) != -1 && isCanceled)

Also add a :

catch (Exception e) {
  Log.e("Error: ", e.getMessage());
}
finaly{ 
    if(isCanceled) 
    {
        // delete file code here
    }
}

You will set this flag to true when you want/need to cancel.

Mario Lenci
  • 10,422
  • 5
  • 39
  • 50
Dan Cuc
  • 76
  • 4
0

set global Boolean flag boolean downloadComplete = false;and in onPostExecute change it to downloadComplete = true; and overrideonDestroy()method. then check flag inonDestroy()` whether file is download or not

if(!downloadComplete)
{
   //then delete file
}

and when you cancel the download then onPostExecute() will not be called so your flag value remain false

T_V
  • 17,440
  • 6
  • 36
  • 48
0

Write below code

@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();
        }
    }
}
Vamshi
  • 1,495
  • 1
  • 15
  • 31