Android pause and resume downloading file to sdcard

user990876 picture user990876 · Oct 12, 2011 · Viewed 8.4k times · Source

I am making an application in which I need to download a file from server and save it to sd card of android device.

Apart of this there is a feature for the user to pause and resume the file.

The problem I am facing is that I am able to download file to sdcard but when try to pause and resume it, it gets starts from the beginning.......

Here is the source ......

public class DownloadWithProgressActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn, pauseButton, resumeButton;
    private ProgressBar bar;
    URLConnection conexion;
    OutputStream output;
    static int count = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button) findViewById(R.id.startBtn);
        pauseButton = (Button) findViewById(R.id.button1);
        resumeButton = (Button) findViewById(R.id.button2);
        bar = (ProgressBar) findViewById(R.id.progressBar1);
        bar.setVisibility(ProgressBar.INVISIBLE);
        bar.setId(0);

        startBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startDownload();
            }
        });
        pauseButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try {
                    output.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        resumeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //  not getting what to write here
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            bar.setVisibility(ProgressBar.VISIBLE);

        }

        @Override
        protected String doInBackground(String... aurl) {
            int downloaded = 0;
            File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
            URL url = null;
            try {
                url = new URL(aurl[0]);
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                conexion = url.openConnection();
                if (file.exists()) {
                    downloaded = (int) file.length();
                    conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");

                }

                else {
                    conexion.setRequestProperty("Range", "bytes=" + downloaded
                            + "-");
                }
            } catch (Exception exception1) {
            }
            conexion.setDoInput(true);
            conexion.setDoOutput(true);

            System.out.println(tryGetFileSize(url));
            conexion.setRequestProperty("Range", "bytes=" + count + "-");
            try {
                conexion.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = null;
            try {
                input = new BufferedInputStream(url.openStream());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                output = new FileOutputStream(file);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            byte data[] = new byte[1024];
            long total = 0;
            try {
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                output.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                input.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
            bar.setProgress(Integer.parseInt(progress[0]));
            System.out.println(Integer.parseInt(progress[0]));
        }

        protected void onPostExecute(String unused) {
        }

        int tryGetFileSize(URL url) {
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("HEAD");
                conn.getInputStream();
                return conn.getContentLength();
            } catch (IOException e) {
                return -1;
            } finally {
                conn.disconnect();
            }
        }

    }
}

Please help.......

Thanks Nikhil

Answer

Viren Savaliya picture Viren Savaliya · Oct 12, 2011
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");

Make "downloaded" as global variable, because download start from this position.

when you press on restart button, check value of this downloaded variable,must not zero all time.