存储访问框架获取正确的Uri路径删除/编辑/获取文件

时间:2017-09-20 15:17:54

标签: android storage-access-framework documentfile

TL:DR; 我解释了如何使用DocumentFile创建文件夹和子文件夹,以及如何删除使用此类创建的文件。 Uri从onActvityResult()返回,而documentFile.getUri.toString()则不一样。我的问题是如何使用有效的Uri来操作文件夹和文件而不使用SAF UI,如果可能的话,不使用hack。

让我分享到目前为止我学到的东西并提出我的问题。 如果你想获得Uri文件夹并对其进行处理,你应该使用IntentACTION_OPEN_DOCUMENT_TREE来获取Uri访问文件夹并为该uri设置W / R权限。

授予 onActivityResult的可持久权限:

final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

如果您选择设备的主文件夹:

Uri treeUri = data.getData();
treeUri.toString()

返回:内容://com.android.externalstorage.documents/tree/primary:

File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "");

返回:存储/模拟/ 0

new File(treeUri.toString()).getAbsolutePath();

返回:内容:/com.android.externalstorage.documents/tree/primary:

如果您使用DocumentFile类获取主文件夹的路径

DocumentFile saveDir = null;
saveDir = DocumentFile.fromFile(Environment.getExternalStorageDirectory());
String uriString = saveDir.getUri().toString();

返回: file:/// storage / emulated / 0

我的第一个问题是如何使用DocumentFile类获取内容的Uri。

我正在构建一个摄影应用程序,默认情况下,我想使用DocumentFile类为图像设置初始文件夹。

 @TargetApi(19)
protected DocumentFile getSaveDirMainMemory() {
    DocumentFile saveDir = null;
    saveDir = DocumentFile.fromFile(Environment.getExternalStorageDirectory());
    // saveDir =
    // DocumentFile.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
    // saveDir =
    // DocumentFile.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));

    DocumentFile newDir = null;
    /*
     * Check or create Main Folder
     */

    // Check if main folder exist
    newDir = saveDir.findFile(DIR_MAIN);

    // Folder does not exist, create it
    if (newDir == null || !newDir.exists()) {
        newDir = saveDir.createDirectory(DIR_MAIN);
    }
    /*
     * Check or create Sub-Folder
     */
    DocumentFile newSubDir = null;

    // Check if sub-folder exist
    newSubDir = newDir.findFile(DIR_SUB);


    // Folder does not exist, create it
    if (newSubDir == null || !newSubDir.exists()) {
        newSubDir = newDir.createDirectory(DIR_SUB);
    }

    if (newSubDir != null && newSubDir.exists()) {
        return newSubDir;
    } else if (newDir != null && newDir.exists()) {
        return newDir;
    } else {
        return saveDir;
    }
}

此方法根据选择在设备的主存储器或PICTURES或DCIM文件夹中创建DIR_MAIN / DIR_SUB。使用此默认文件夹,我将图像保存到此创建的子文件夹。 我得到newSubDir.getUri()。toString(): file:/// storage / emulated / 0 / MainFolder / SubFolder 我将DIR_MAIN命名为MainFolder,DIR_SUB:SubFolder进行测试。

要访问或删除图像,我使用此路径和图像名称创建为

DocumentFile imageToDeletePath = DocumentFile.fromFile(new File(lastSavedImagePath));
DocumentFile imageToDelete = imageToDeletePath.findFile(lastSavedImageName);

imageDelete返回null,因为Uri的格式不正确。

如果我打开SAF ui并获取UI onActivityResult并将其保存为字符串我使用此方法获取目录并检查Uri权限

@TargetApi(19)
protected DocumentFile getSaveDirNew(String uriString) {
    DocumentFile saveDir = null;

    boolean canWrite = isUriWritePermission(uriString);

    if (canWrite) {
        try {
            saveDir = DocumentFile.fromTreeUri(MainActivity.this, Uri.parse(uriString));
        } catch (Exception e) {
            saveDir = null;
        }
    }

    return saveDir;
}

检查字符串中的Uri是否具有写入权限,如果您不接受或删除可持久权限,则可能没有。

private boolean isUriWritePermission(String uriString) {
    boolean canWrite = false;

    List<UriPermission> perms = getContentResolver().getPersistedUriPermissions();
    for (UriPermission p : perms) {
        if (p.getUri().toString().equals(uriString) && p.isWritePermission()) {
            Toast.makeText(this, "canWrite() can write URI::  " + p.getUri().toString(), Toast.LENGTH_LONG).show();
            canWrite = true;
            break;
        }
    }
    return canWrite;
}

使用有效的uri保存图像并使用

DocumentFile imageToDeletePath = DocumentFile.fromTreeUri(this, Uri.parse(lastSavedImagePath));
DocumentFile imageToDelete = imageToDeletePath.findFile(lastSavedImageName);

1 个答案:

答案 0 :(得分:1)

Uri.fromFile()DocumentFile.fromTreeUri()从两个不同的世界中创建uri。

尽管它们目前看起来非常相似,但这只是巧合,并且可能会在将来的任何Android版本中更改。

没有从一种转换为另一种的“非hacky”方式。如果您想要一个肮脏的解决方案,可以进行反思(查看DocumentFile.fromTreeUri的源代码,并可能在较新的Android版本上使用Storage类。

另请参阅: Android - Storage Access Framework - Uri into local file