【问题标题】:Android: storing files in DownloadsAndroid:将文件存储在下载中
【发布时间】:2021-03-06 01:47:00
【问题描述】:

在 Android 10 和范围存储中,无法再使用 Environment.getExternalStoragePublicDirectory()。 还有多个其他选项,包括 MediaStore 和 Storage Access Framework。 我们的电子邮件应用程序只想将新文件附加到下载集合中。我们必须在本地对它们进行预处理,这样我们就不能使用 DownloadManager。

MediaStorage guide 提及

注意:尽管可以将通用文件存储在 Documents/ 文件夹或 Download/ 文件夹中(包括非媒体文件),但对于这些用例,最好使用存储访问框架 (SAF)。

但据我从Storage Access Framework guide 了解到的,我们必须在每次用户想要下载文件时提示用户,这似乎没有必要。

将文件附加到下载的常见做法是什么?

【问题讨论】:

  • 对于 Android 10 设备,只需在清单中请求旧版外部存储即可。然后它像以前一样工作。
  • we would have to prompt user each time when they want to download the file and it seems unnecessary. 文件?还是文件?不。让用户选择一个目录,然后您可以在其中创建任意数量的文件。
  • 一个文件,谢谢。如果他们选择了错误的目录,他们会在以后找到它吗?我们现在使用 MediaStorage,它是下载集合。
  • blackapps 是错误的,并且像往常一样,没有提供任何解决方案。 Android 10 在访问方面完全是一团糟,Android 11 试图在某种程度上纠正这一点,但情况只会变得更糟。您将只能读取/写入位于您的应用程序“文件空间”中的文件。在此之外需要的任何特殊权限,例如备份应用程序等,都需要谷歌批准。例如,我的应用程序在尝试创建音乐播放列表或读/写 mp3 标签时已经损坏

标签: android mediastore storage-access-framework


【解决方案1】:

无论API级别如何,您都可以将下载的文件保存到Download文件夹:

FileDescription file = new FileDescription(fileName, subFolder, mimeType);
Uri fileUri = DocumentFileCompat.createDownloadWithMediaStoreFallback(context, file);

使用fileUri 打开输出流并将数据写入其中。

无论如何,DocumentFileCompat 只能在SimpleStorage 中使用。

【讨论】:

  • 感谢您的链接,但最好的办法是找出 SimpleStorage 的功能并在此处进行解释。
【解决方案2】:

这是一个在下载文件夹中写入 à 文件的示例:

   OutputStream out;

   ContentResolver contentResolver = getContext().getContentResolver();

   ContentValues contentValues = new ContentValues();
   contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, localPath);
   contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
   contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_DOWNLOADS);
   Uri uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues);
   out = contentResolver.openOutputStream(uri);

【讨论】:

  • 我做了类似的事情,但你不需要RELATIVE_PATH,它只用于子文件夹。
猜你喜欢
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2017-12-05
  • 2017-02-15
  • 1970-01-01
相关资源
最近更新 更多