转载地址:http://blog.csdn.net/ITCEOjingying/article/details/6373016

Android作为一个手机操作系统,在Android中访问网络是许多应用程序都必需的功能。用户也经常需要在应用程序中下载所需要的文件比如电子书,MP3格式的音乐文件,电影等。

Android文件下载的一般步骤:

1、创建一个HttpURLConnection的对象

URL url=new URL(urlStr);

HtttpURLConnection urlConn=(HtttpURLConnection)url.OpenConnection();

2、获取一个InputStream输入流对象

urlConn.getInputStream();

3、在AndroidManifest.xml中添加网络访问权限

4、在AndroidManifest.xml中加入访问SDCard的权限

5、创建文件流FileOutputStream,将从InputStream读出的数据写入到FileOutputStream。

需要注意的是在Android3.0之前的Android平台上可以直接Activity所在的线程中访问网络,下载网络上的文件。但是这样的话,如果下载的文件较大,或者网速比较慢的情况下,Activity界面就会处于无法及时响应用户操作的状态。Android3.0中如果在Activity所在的线程访问网络,调试执行时会出现异常信息:“android.os.NetworkOnMainThreadException”,无法获取有效的HttpURLConnection对象。所以我们需要把访问网络,下载文件的操作放在另外的线程中。

示例:

新建一个Android应用程序项目。在main.xml总添加两个Button:buttontxt、buttonmp3。点击分别下载txt和mp3文件。下载的txt文件直接将txt文本文件的内容直接输出到控制台。mp3文件保存到虚拟结的SD卡目录下的Android文件夹中。为了下载方便,项目中下载的a.txt和music.mp3文件均放在本机安装的tomcat服务器上webapps目录下的Android文件夹中。

main.xml

view plain copy to clipboard print ?
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello"
  11. />
  12. <Button
  13. android:id="@+id/buttontxt"
  14. android:layout_width="300dp"
  15. android:layout_height="wrap_content"
  16. android:text="单击下载txt文件"
  17. />
  18. <Button
  19. android:id="@+id/buttonmp3"
  20. android:layout_width="300dp"
  21. android:layout_height="wrap_content"
  22. android:text="单击下载mp3文件"
  23. />
  24. LinearLayout>
<?xml version="1.0" encoding="utf-8"?>