首先网络连接设置权限:
<!-- 在SD卡中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 向SD卡写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 授权访问网络 -->
<uses-permission android:name="android.permission.INTERNET" />
布局:xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="要下载的资源的URL:"
/>
<EditText
android:id="@+id/url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://music.baidu.com/data/music/file?link=http://
zhangmenshiting.baidu.com/data2/music/87713529/87600807226800128.mp3
?xcode=24b1557ad2119ecba951d1832bfd71b2ebcd79ff87c48871"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="目标文件:"
/>
<EditText
android:id="@+id/target"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="/mnt/sdcard/a.mp3"
/>
<Button
android:id="@+id/down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/down"
/>
<!-- 定义一个水平进度条,用于显示下载进度 -->
<ProgressBar
android:id="@+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
style="?android:attr/progressBarStyleHorizontal"
/>
</LinearLayout>
下载工具类:
/**
*
*/
package com.jiaruihuademo.download;
import java.io.InputStream;
import java.io.Rando