The best way to download and pause ,resume a big file in android?

Farshid roohi picture Farshid roohi · May 9, 2017 · Viewed 7.4k times · Source

I need to download a big file on my app (almost 1gb) and i was wondering what is the best way to do that and some libs to help me. First I looked the Android Asynchronous Http Library but I didn't find examples showing how to publish the progress or start, pause download. Then I don't know if should I use this lib or just use a standart http commons. Other problem is, should I use a service to download my file??

Answer

Behzad Ashrafian picture Behzad Ashrafian · May 9, 2017

You can use this code in asynctask to download with resume:

@SuppressLint("Wakelock")
    @Override
    protected String doInBackground(String... sUrl) {
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        wl.acquire();

        try {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                File SDCardRoot = Environment.getExternalStorageDirectory();                    
                File file = new File(SDCardRoot,FOLDER_PATH1+FOLDER_PATH2+ "/"+fileName);
                int downloaded=0;
                if(file.exists()){
                    downloaded=(int) file.length();
                    connection.setRequestProperty("Range", "bytes=" + (int) file.length() + "-");
                }
                else{
                    file.createNewFile();
                }
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report 
                // instead of the file


                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength()+(int)file.length();
                // download the file
                input = connection.getInputStream();      
                if(downloaded>0){
                    output = new FileOutputStream(file,true);
                }
                else{
                    output = new FileOutputStream(file);
                }
                byte data[] = new byte[1024];
                long total = downloaded;
                int count;
                mProgressDialog.setMax(fileLength/1024);
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled())
                        return null;
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int)total/1024);
                    output.write(data, 0, count);
                }
                output.flush();
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
                if (connection != null)
                    connection.disconnect();
                wl.release();
                return null;
            } catch (Exception e) {
                return e.toString();
            }
        }
        catch (Exception e) {
            return e.toString();
        }        
    }