0

在我的测试中,我发现在 5.0+ 上DocumentFile创建的fromFile任何写入( 、 等)都会失败createFilecreateDirectory即使您拥有 SAF 的 root 权限。

这是预期的行为吗?

如果fromFile仅适用于 <5.0 的兼容性,我真的希望他们能在文档中明确这一点。

4

2 回答 2

0

因此fromFile生成一个RawDocumentFile,它似乎只是包装一个文件。我看不出这将如何提供任何额外的写入权限File,而不管 SAF 权限如何,它本身都没有,所以我要说这fromFile应该仅作为向后兼容 (<4.4) 工厂。我已提交增强请求以更新文档以解释这一点。

于 2016-02-07T10:21:06.233 回答
0

如果您不想使用 ACTION_OPEN_DOCUMENT_TREE 或 ACTION_OPEN_DOCUMENT 来获取 Uri,您可以使用以下从 API19(Android4.4-Kitkat) 到 API28(Android8-Oreo) 有效的方法将 FILE 转换为 Uri (SAF):

 /**
 * Ing.N.Nyerges 2019 V2.0
 *
 * Storage Access Framework(SAF) Uri's creator from File (java.IO),
 * for removable external storages
 *
 * @param context Application Context
 * @param file File path + file name
 * @return Uri[]:
 *   uri[0] = SAF TREE Uri
 *   uri[1] = SAF DOCUMENT Uri
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static Uri[] getSafUris (Context context, File file) {

    Uri[] uri = new Uri[2];
    String scheme = "content";
    String authority = "com.android.externalstorage.documents";

    // Separate each element of the File path
    // File format: "/storage/XXXX-XXXX/sub-folder1/sub-folder2..../filename"
    // (XXXX-XXXX is external removable number
    String[] ele = file.getPath().split(File.separator);
    //  ele[0] = not used (empty)
    //  ele[1] = not used (storage name)
    //  ele[2] = storage number
    //  ele[3 to (n-1)] = folders
    //  ele[n] = file name

    // Construct folders strings using SAF format
    StringBuilder folders = new StringBuilder();
    if (ele.length > 4) {
        folders.append(ele[3]);
        for (int i = 4; i < ele.length - 1; ++i) folders.append("%2F").append(ele[i]);
    }

    String common = ele[2] + "%3A" + folders.toString();

    // Construct TREE Uri
    Uri.Builder builder = new Uri.Builder();
    builder.scheme(scheme);
    builder.authority(authority);
    builder.encodedPath("/tree/" + common);
    uri[0] = builder.build();

    // Construct DOCUMENT Uri
    builder = new Uri.Builder();
    builder.scheme(scheme);
    builder.authority(authority);
    if (ele.length > 4) common = common + "%2F";
    builder.encodedPath("/document/" + common + file.getName());
    uri[1] = builder.build();

    return uri;
}
于 2019-07-15T22:46:36.157 回答