Android SAF(存储访问框架): Get particular file Uri from TreeUri

标签 android file-io android-sdcard storage-access-framework

我正在获取外部 SD 卡的 PersistableUriPermission 并将其存储以供进一步使用。 现在我希望当用户从我的应用程序的文件列表中向我提供文件路径时,我想编辑文档并重命名它。

所以我有要编辑的文件的文件路径。

我的问题是如何从我的 TreeUri 中获取该文件的 Uri 以便编辑文件。

最佳答案

访问SD卡的文件

使用DOCUMENT_TREE对话框获取SD卡的Uri

告知用户如何在对话框中选择sd-card。 (配图或gif动图)

// call for document tree dialog
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);

onActivityResult 上,您将拥有选定的目录 Uri。 (sdCardUri)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_OPEN_DOCUMENT_TREE:
            if (resultCode == Activity.RESULT_OK) {
                sdCardUri = data.getData();
             }
             break;
     }
  }

现在必须检查用户是否,

一个。选择了 SD 卡

选择我们的文件所在的 SD 卡(某些设备可能有多个 SD 卡)。


我们通过层次结构查找文件来检查 a 和 b,从 sd 根目录到我们的文件。如果找到文件,则a条件和b条件都具备。

//First we get `DocumentFile` from the `TreeUri` which in our case is `sdCardUri`.
DocumentFile documentFile = DocumentFile.fromTreeUri(this, sdCardUri);

//Then we split file path into array of strings.
//ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "myImage.jpg"}
// There is a reason for having two similar names "MyFolder" in 
//my exmple file path to show you similarity in names in a path will not 
//distract our hiarchy search that is provided below.
String[] parts = (file.getPath()).split("\\/");

// findFile method will search documentFile for the first file 
// with the expected `DisplayName`

// We skip first three items because we are already on it.(sdCardUri = /storage/extSdCard)
for (int i = 3; i < parts.length; i++) {
    if (documentFile != null) {
        documentFile = documentFile.findFile(parts[i]);
    }
  }

if (documentFile == null) {

    // File not found on tree search
    // User selected a wrong directory as the sd-card
    // Here must inform the user about how to get the correct sd-card
    // and invoke file chooser dialog again.  

    // If the user selects a wrong path instead of the sd-card itself,  
    // you should ask the user to select a correct path.  
    // I've developed a gallery app with this behavior implemented in it.  
    // https://play.google.com/store/apps/details?id=com.majidpooreftekhari.galleryfarsi
    // After you installed the app, try to delete one image from the  
    // sd-card and when the app requests the sd-card, select a wrong path  
    // to see how the app behaves.  

 } else {

    // File found on sd-card and it is a correct sd-card directory
    // save this path as a root for sd-card on your database(SQLite, XML, txt,...)

    // Now do whatever you like to do with documentFile.
    // Here I do deletion to provide an example.


    if (documentFile.delete()) {// if delete file succeed 
        // Remove information related to your media from ContentResolver,
        // which documentFile.delete() didn't do the trick for me. 
        // Must do it otherwise you will end up with showing an empty
        // ImageView if you are getting your URLs from MediaStore.
        // 
        Uri mediaContentUri = ContentUris.withAppendedId(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                longMediaId);
        getContentResolver().delete(mediaContentUri , null, null);
    }


 }

我的应用程序的 SD 卡路径选择行为错误:

要检查在错误的 SD 卡路径选择上的行为,请安装应用程序并尝试删除 SD 卡上的图像并选择错误的路径而不是 SD 卡目录。
日历画廊:https://play.google.com/store/apps/details?id=com.majidpooreftekhari.galleryfarsi

注意:

您必须在 list 中提供对外部存储的访问权限,并在应用程序中为 os>=Marshmallow 提供访问权限。 https://stackoverflow.com/a/32175771/2123400


编辑SD卡的文件

对于编辑 SD 卡上的现有图像,如果您想调用另一个应用程序来为您执行此操作,则不需要上述任何步骤。

在这里,我们调用所有具有编辑图像功能的 Activity (来自所有已安装的应用程序)。 (程序员在 list 中标记他们的应用程序,因为它能够提供来自其他应用程序( Activity )的可访问性)。

在你的 editButton 点击​​事件上:

String mimeType = getMimeTypeFromMediaContentUri(mediaContentUri);
startActivityForResult(Intent.createChooser(new Intent(Intent.ACTION_EDIT).setDataAndType(mediaContentUri, mimeType).putExtra(Intent.EXTRA_STREAM, mediaContentUri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Edit"), REQUEST_CODE_SHARE_EDIT_SET_AS_INTENT);

这是获取 mimeType 的方法:

public String getMimeTypeFromMediaContentUri(Uri uri) {
    String mimeType;
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        ContentResolver cr = getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                .toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    }
    return mimeType;
}

注意:

在 Android KitKat(4.4) 上不要要求用户选择 sd 卡,因为在这个版本的 Android 上 DocumentProvider 不适用,因此我们没有机会访问 sd -卡用这种方法。 查看 DocumentProvider 的 API 级别 https://developer.android.com/reference/android/provider/DocumentsProvider.html
我找不到任何适用于 Android KitKat(4.4) 的东西。如果您发现任何对 KitKat 有用的信息,请与我们分享。

在低于 KitKat 的版本中,操作系统已经提供了对 SD 卡的访问权限。

关于Android SAF(存储访问框架): Get particular file Uri from TreeUri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39054454/

相关文章:

android - 设置android :text to @+id/xyz的意义

c++ - 在 C++ 中读取二进制文件而不将整个文件缓冲到内存中

c++ - 为什么这段代码没有给出任何输出?这似乎是一个无限循环

android - 停止使用 Android 原生相机保存照片

android - 将文本文件写入 SD 卡失败

java - 日期字符串的正确日期格式,例如 "2013-11-16T08:46:00.000-06:00"

java - 为什么 BitmapFactory.decodeByteArray 返回 null?

android - Android同时在不同的耳机上播放两首不同的歌曲

python - 在目录中查找最旧的文件(递归)

android - windows下eclipse安卓模拟器的SD卡在哪里?