In my application downloading loads of files from web they were around 200Mb files(Zipped). How do I download files programmatically in Android? Actually my concern is about performance of code. How do I handle errors and network problem in between?
Asked
Active
Viewed 1.3k times
2 Answers
17
Here's some code that I recently wrote just for that:
try {
URL u = new URL("http://your.url/file.zip");
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "file.zip"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
This downloads the file and puts it on your sdcard.
You could probably modify this to suit your needs. :)

xil3
- 16,305
- 8
- 63
- 97
-
I think 1024 (1K) bytes buffer isn't the "best way"? 1500 is better, I also tried 5000 and it was faster. – Derzu Jul 04 '13 at 01:54
-
I think 4096 is better – Smile Feb 28 '14 at 17:29
2
I'd like to point out that Android 2.3 (API Level 9) introduces a new system service called the DownloadManager
. If you're OK with only supporting 2.3, then you should definitely use it. If not, you can either:
- Check if the
DownloadManager
is available and use it if it is. If it's not (Android < 2.3), download the file yourself, for example as described by xil3. - Don't use
DownloadManager
at all, if you think it's too much work. However, I strongly believe you will benefit from its use.

Felix
- 88,392
- 43
- 149
- 167
-
DownloadManager is totally undone to developers work with it. You will have more trouble than benefits if you use it to something more than just 1 activity and 1 file to download – Sever Nov 06 '13 at 13:14
-
Hi, can DownloadManager handle somethings like download interrupt, resume download, scheduled download, multiple files download? I've tried DownloadManager for a while but I just can download 1 file at a time, and when download is interrupt, I have to download all again. Thanks – 0xh8h Jun 26 '14 at 02:39