Downloading a large list of files in the background on Android
<p>I have an app that allows the user to cache data for offline use.
The data I need to download is mostly images, but includes other things like videos, text files &amp; mp3s. There may be as little as 20 files to download or upwards of 300 or more. The files range from a few kilobytes to several megs in the case of videos.</p>

<p>I've tried using a service with a looper, and a service with a plain old thread, but even if I use startForeground on the service it inevitably gets killed with a "timeout executing service" and an ANR after about 10 files or so on both my Droid and my Incredible.</p>

<p>When I get the ANR it seems that the user system is around 45-50% cpu usage. The service restarts after a while and continues, but I need the downloads to take precedence in most cases.</p>

<p>Here's the code to actually download a file, which is run in a thread:</p>

<pre><code>try {
    URL request = new URL(entry.remotePath);
    InputStream is = (InputStream) request.getContent();
    FileOutputStream fos = new FileOutputStream(entry.localPath);
    try {
        byte[] buffer = new byte[4096];
        int l;
        while ((l = is.read(buffer)) != -1) {
            fos.write(buffer, 0, l);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        is.close();
        fos.flush();
        fos.close();
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
</code></pre>

<p>My question is, is there a standard way to do this (podcast apps like ACast seem to download a lot of data through a service with no issue), or do I have the right approach but am doing something incorrectly causing an overload to the system. Should my service thread be sleeping between downloads, or anything special I can do to meter it to keep cpu low or let the system know it's still working?</p>

<p>I'm targeting System 8 and above, if that matters.</p>
