开发者

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 Andro开发者_StackOverflow中文版id? Actually my concern is about performance of code. How do I handle errors and network problem in between?


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


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:

  1. 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.
  2. Don't use DownloadManager at all, if you think it's too much work. However, I strongly believe you will benefit from its use.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜