6

I have an async downloader in my app, but sometimes the connection is lost, especially when I'm on a mobile connection and if the file is a large one (>10 MB). Is there a way to catch when a download stops and then force it to resume with the result of completing the download?

This is the async task doInBackground:

protected String doInBackground(String... aurl) {
    int count;

    try {

        URL url = new URL(aurl[0]);
        URLConnection conexion = url.openConnection();
        // conexion.setRequestProperty("Range", "bytes=" + downloaded + "-");
        conexion.connect();

        int lenghtOfFile = conexion.getContentLength();
        pesoVideo = lenghtOfFile / 1048576;
        output = "/sdcard/" + folderString + "/" + nomeFile + ".mp3";
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(
        VideoDownloaderBrowserActivity.this.output);

        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) {
    }

    return null;
}

This is the onProgressUpdate:

protected void onProgressUpdate(String... progress) {
    if (Integer.parseInt(progress[0]) > progresso) {
        ...
    }
}
Blizzer
  • 260
  • 4
  • 22
Shark812
  • 81
  • 4
  • 1
    You could use downloadmanager to download the files over http. It does the retry for you if the connection is lost – nandeesh Aug 07 '12 at 09:25
  • 1
    The download manager is a system service that handles long-running HTTP downloads.here is reference link:[downloadmanager](http://developer.android.com/reference/android/app/DownloadManager.html) – tigger Aug 07 '12 at 10:02
  • thanks for the tip but it will keep working on device with Android 2.2 or lower? – Shark812 Aug 07 '12 at 11:25
  • Tip: write code in english. This way, you increase the chances of another person understanding it. Especially when posting it to stackoverflow. – jontejj May 02 '13 at 14:58

1 Answers1

0

Here is a thread discussing resumable downloading in Android below API 9. Otherwise DownloadManager is a good option too for newer versions.

Basically you need to enable byte serving on your server to allow for the resumable downloading.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135