gpt4 book ai didi

android - 在 Android 中从 File Api 迁移到 Storage Access Framework (SAF)

转载 作者:行者123 更新时间:2023-12-04 23:49:54 26 4
gpt4 key购买 nike

由于 Android 11 和范围存储,我必须开始使用存储访问框架 (SAF),但我有很多源代码可用于 File API . 问题一 : 我是否必须重写所有内容才能使用 DocumentFile ?
伪用例:
用户创建并选择自己的目录,系统返回 Uri :

//Start pick a directory
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, requestCode)

...

onActivityResult {
//check requestCode + resultCode
...
//get Uri
val selectedDir = data.getData();
if (selectedDir == null) {
return;
}
//take persist permission for later use
getContentResolver().takePersistableUriPermission(selectedDir, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
现在我有 Uri具有读/写持久权限的用户选择的文件夹。
来自 Android doc

To help your app work more smoothly with third-party media libraries, Android 11 allows you to use APIs other than the MediaStore API to access media files from shared storage using direct file paths. These APIs include the following:
The File API.
Native libraries, such as fopen().


问题2 : 好吧,我该如何使用 File API ,当我有一个 Uri来自 ACTION_OPEN_DOCUMENT_TREE ?
问题3 :这是否意味着我必须复制所有代码才能使用 requestLegacyExternalStorage 复制到 Android 9(或 10 与 File API )从 Android 11+ 开始,使用 SAFUri ?
目标是:使用 File API 保留代码,但获得对用户选择的目录的读/写权限。
更新
经过大量测试 DocumentFile在实践中不适用。也许只有几个文件。 DocumentFile创建不必要的复杂源代码,并且非常缓慢 related topic .
例如,通过 File API 创建 1000 个目录~350ms 和通过 DocumentFile ~2300 毫秒。删除和检查文件是否存在总是很慢。
来自 Scoped Storage Recap

Awesome! It would be really great to have some kind of support library or Androidx lib for file handling.


谷歌开发者的回答是:

We're exploring this option as an experiment, stay tuned 😉

最佳答案

请注意,不推荐使用 startActivityForResult()。而是应使用 registerForActivityResult()。不幸的是,我还没有为这种机制找到任何可用的 Java 示例。甚至 Google 的示例代码仍在使用已弃用的功能。我会很高兴任何提示。
PS:还有一些 ActivityResultContracts.OpenDocumentTree() 函数可能会有所帮助,但我也找不到如何使用它的示例。

关于android - 在 Android 中从 File Api 迁移到 Storage Access Framework (SAF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67269439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com