Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download files from net programmatically in Android?

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?

like image 434
Srinivas Avatar asked Feb 04 '11 09:02

Srinivas


People also ask

How do I download files on Android?

Go to the webpage where you want to download a file. Touch and hold what you want to download, then tap Download link or Download image. To see all the files you've downloaded to your device, open the Downloads app.

How do I download using Download Manager?

How to Use Internet Download Manager. From the main interface, you can see multiple control buttons. To download new file, simply click Add URL and paste the link to the file that you wish to download. Start downloading by clicking the Start/Resume button.


1 Answers

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. :)

like image 174
xil3 Avatar answered Sep 29 '22 12:09

xil3