Recently, I implemented some code to download some audio assets that are packaged in a .zip file. When first run, the app downloads these assets from a server (S3 in our case), unpacks them, and stashes them away on the SD card.
This is a typical use case for apps such as games, which have a lot of image and audio assets that must be downloaded separately from the application APK file. This is usually because Google enforces a 50-megabyte limit for Android APK downloads. But also it can be a way to put some of your application on the SD card if you cannot support SD card installation for some reason or another.
Being a lazy developer who works under tight deadlines, I went out searching for some code to unpack .zip files. I found one example that was a good starting point, but it ran very slowly and it didn’t clean up after itself well when it was done.
I have built on that example, and produced a working example app for Android that shows how to implement a background task that will download a .zip file from an internet URL, then unzip the contents to a cache folder on external storage (a.k.a the SD card).
The sample app:
- Traps errors and cleans up after itself in the event of error
- Performs all I/O operations (network and filesystem) in the background, for StrictMode compliance
- Keeps the screen alive while the download is in process
- Locates the files on external storage in a place which will be automatically deleted by Android on uninstall
- Uses buffered I/O for efficiency
- Manages internal data in a way as to (mostly) be friendly to the Dalvik garbage collector.
- Is compatible with all versions of Android 2.1 through 4.0. It probably will run on earlier versions of Android, but I haven’t tested.
In short, it is production-ready code.
The sample code is published under the MIT open-source license, and is available on my github repository.