阅读量:3
在Android中,可以使用以下几种方式实现文件下载功能:
- 使用HttpURLConnection或OkHttp库发送HTTP请求并获取文件内容,然后将文件保存到本地存储中。示例代码如下:
public class FileDownloader { public static void downloadFile(String fileUrl, String destinationPath) { try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(destinationPath); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
使用方法:
FileDownloader.downloadFile("http://example.com/file.txt", "/sdcard/file.txt");
- 使用DownloadManager系统服务进行文件下载,它提供了下载的管理和控制功能。示例代码如下:
public class FileDownloader { public static void downloadFile(Context context, String fileUrl, String fileName) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(fileUrl); DownloadManager.Request request = new DownloadManager.Request(uri); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); long downloadId = downloadManager.enqueue(request); } }
需要添加以下权限到AndroidManifest.xml文件中:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用方法:
FileDownloader.downloadFile(context, "http://example.com/file.txt", "file.txt");
- 使用第三方库,如Retrofit或Volley,它们提供了更高级的网络请求和下载功能。具体实现方式请参考相关文档和示例代码。