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" />