3

I am using an AsyncTask like this:

public class DownloadTask extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        String fileName=null;
        public DownloadTask(Context context,ProgressDialog Dialog) {
            this.context = context;
            this.mProgressDialog=Dialog;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }


                String raw = connection.getHeaderField("Content-Disposition");

             if(raw != null && raw.indexOf("=") != -1) {
                  fileName = raw.split("=")[1];
                  fileName=fileName.split(";")[0];
                  fileName=fileName.substring(1, fileName.length()-1);
             } else {

             }
                File f=new File(context.getFilesDir()+"/"+fileName);
               if(!f.exists())
               {Log.d("TAG","DOES NOT EXIST , downloading");

                int fileLength = connection.getContentLength();

                input = connection.getInputStream();

                Log.d("Tag", raw);
                Log.d("Tag",fileName);
                output = new FileOutputStream(context.getFilesDir()+"/"+fileName);

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        File check =new File(context.getFilesDir()+"/"+fileName);
                        check.delete();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) 
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } }catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)

                    connection.disconnect();


            }
            return null;


        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                 getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (result != null)
                Toast.makeText(context,"Download error: "+"Please check your internet connection!", Toast.LENGTH_LONG).show();
            else
            { Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
            Intent i=new Intent(context,MuPDFActivity.class);
            Uri uri=Uri.parse(context.getFilesDir()+"/"+fileName);
            i.setAction(Intent.ACTION_VIEW);
            i.setData(uri);
            context.startActivity(i);
            }
        }}

This effectively works when I call this from my activity, and the files are downloaded. But, If the download is interrupted(if user opens the list of open apps and force quits), The partially downloaded file remains , and is currupt. I dont want to resume the download,I want to delete the file if the download had been interrupted. How do I do that?

harveyslash
  • 5,906
  • 12
  • 58
  • 111

2 Answers2

1

if the user even presses the home button or rotate your device your download is interrupted. So in onStop() method you must check the file not in onPostExecute(String result) because it may not call and may be it continue to download. you can just check end of file to see if it has EOF or not and SharedPreferences not require.

mmlooloo
  • 18,937
  • 5
  • 45
  • 64
  • My app does has only one orientation mode, so i need not worry about rotation atleast – harveyslash Aug 04 '14 at 16:34
  • Okay but what to do with home button? how your solution is going to handle it? i think you wont get result but you can try !! – mmlooloo Aug 04 '14 at 16:36
  • I am using an asyncTask, so there is no problem with the code running in the background. problems start only if the app is quit forcefully – harveyslash Aug 04 '14 at 16:38
0

jitain sharma's idea of solution of cancelling the asynctask did not work(when force quitting the app, its not called).

So, in the end, I used sharedPreferences to 'mark' the end of file download in my AsyncTask's onPostExecute() method.I am just checking for the result, if all is fine(then string will be null), I am adding a SharedPreference with the file name with the value "DONE".

Before executing the AsyncTask, I am checking if file exists AND if the sharedPreference exists.

public class DownloadTask extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        String fileName=null;
        public DownloadTask(Context context,ProgressDialog Dialog) {
            this.context = context;
            this.mProgressDialog=Dialog;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(3000);
                connection.setConnectTimeout(5000);
                connection.connect();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }


                String raw = connection.getHeaderField("Content-Disposition");

             if(raw != null && raw.indexOf("=") != -1) {
                  fileName = raw.split("=")[1];
                  fileName=fileName.split(";")[0];
                  fileName=fileName.substring(1, fileName.length()-1);
             } else {

             }
                File f=new File(context.getFilesDir()+"/"+fileName);
               if(!f.exists())
               {Log.d("TAG","DOES NOT EXIST , downloading");

                int fileLength = connection.getContentLength();

                input = connection.getInputStream();

                Log.d("Tag", raw);
                Log.d("Tag",fileName);
                output = new FileOutputStream(context.getFilesDir()+"/"+fileName);

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        File check =new File(context.getFilesDir()+"/"+fileName);
                        check.delete();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) 
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } }catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)

                    connection.disconnect();


            }
            return null;


        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                 getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (result != null)
            {File file=new File(context.getFilesDir()+File.separator+fileName);
            file.delete();
                Toast.makeText(context,"Download error: "+"Please check your internet connection!", Toast.LENGTH_LONG).show();
            }
    //**THIS IS THE CHANGE**           else
            { SharedPreferences p=PreferenceManager.getDefaultSharedPreferences(context);
            Editor editor=p.edit();
           editor.putString(fileName, "DONE");
           editor.commit();


                    Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
            Intent i=new Intent(context,MuPDFActivity.class);
            Uri uri=Uri.parse(context.getFilesDir()+"/"+fileName);
            i.setAction(Intent.ACTION_VIEW);
            i.setData(uri);
            context.startActivity(i);
            }
        }}

And here is how I am checking:

if(!file.exists()||!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).contains(fileName))

{ new File(getFilesDir()+File.separator+"phychap1.pdf").delete(); }

I am always open to better solutions

harveyslash
  • 5,906
  • 12
  • 58
  • 111