Android实现文件下载功能可以使用以下步骤:
<uses-permission android:name="android.permission.INTERNET" />
public class DownloadFileTask extends AsyncTask<String, Integer, String> {
private Context mContext;
public DownloadFileTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(String... params) {
String fileUrl = params[0];
String fileName = params[1];
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// 获取文件大小
int fileLength = connection.getContentLength();
// 创建输入流
InputStream input = new BufferedInputStream(url.openStream());
// 创建输出流
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);
byte[] data = new byte[1024];
int total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// 发布进度信息
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
// 关闭流
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
return "下载失败";
}
return "下载成功";
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// 更新下载进度
Log.d("Download progress", progress[0] + "%");
}
}
String fileUrl = "http://example.com/file.txt";
String fileName = "file.txt";
DownloadFileTask downloadTask = new DownloadFileTask(this);
downloadTask.execute(fileUrl, fileName);
上述步骤中,需要注意的是,文件下载需要在后台线程中进行,所以使用了AsyncTask来执行下载操作。另外,记得在AndroidManifest.xml文件中添加存储空间访问权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />