android - 如何将文件从 Firebase 存储 url 下载到内部存储
问题描述
我想从 URL 下载 pdf 文件,我无法下载它显示不支持的路径。如何设置正确的路径。
public void downloadAndOpenPdf(String url){
String fileName = url.substring(url.lastIndexOf('/')+1, url.length());
file = new File(Environment.getDataDirectory(), fileName);
if(!file.isFile()) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.setDestinationUri(Uri.fromFile(file));
// req.setTitle("Some title");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
if (file.exists()) {
openPdfDocument(file);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
dm.enqueue(req);
Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
}
else {
openPdfDocument(file);
}
}
public boolean openPdfDocument(File file) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(target);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
return false;
}
}
解决方案
如果您要从 Firebase 存储下载文件,请尝试使用此代码
private void getFileUrl(){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("your file name as is from firebase storage");
storageReference.getDownloadUrl().addOnSuccessListener(uri -> {
String url = uri.toString();
downloadFile(getContext(), "your file name", "file extension", DIRECTORY_DOWNLOADS, url);
mProgressBar.hide();
}).addOnFailureListener(e -> {
mProgressBar.hide();
ToastUtil.toastLong(getContext(), "something went wrong " + e.getMessage());
});
}
private void downloadFile(Context context, String fileName, String fileExtension, String destinationDirectory, String url) {
DownloadManager downloadmanager = (DownloadManager) context.
getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtension);
downloadmanager.enqueue(request);
}
让我知道它是否有效。
推荐阅读
- android - 如何使用 Android Studio 调试系统应用
- c# - 创建 REST API 扩展 SQL Server
- html - 在@media CSS 查询上设置透明悬停的问题
- algorithm - 就空间复杂度而言,哪种排序算法最好——快速排序还是插入排序?
- laravel - 如何在 laravel 中使用 post 方法创建 api
- graph - Tensor("Placeholder:0", shape=(?, 28, 28, 1), dtype=float32) 必须与 Tensor("W0:0", shape=(5, 5, 1, 6) 来自同一图表, dtype=float32_ref)
- maven - 为什么 IntelliJ 在我的 Spring Boot 项目中添加了错误的 maven 依赖项?
- deployment - 如何在 Corda 的 deployNodes 任务中添加 h2Settings?
- swift - 无法赋值:“setText”是一种方法
- javascript - 如何使用javascript获取从java类传递到本机脚本jar文件的变量数据