写一段android 下载文件流到本地并于下载完成打开文件所在路径的文件夹的代码
时间: 2024-02-21 15:02:28 浏览: 127
Android 将文件下载到指定目录的实现代码
5星 · 资源好评率100%
好的,以下是一段参考代码:
```java
public void downloadFile(String url, String fileName) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(fileName);
request.setDescription("Downloading " + fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(request);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String fileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
openFile(fileUri);
}
}
cursor.close();
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private void openFile(String fileUri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(fileUri), "application/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(intent, "Open File"));
}
```
这段代码使用了 Android 的 DownloadManager 下载文件,然后在下载完成后通过 BroadcastReceiver 打开文件所在路径的文件夹。注意需要在 AndroidManifest.xml 文件中添加文件读写权限和下载权限。
阅读全文