Storage Access Framework-永久权限授予在用户选择的文件夹上失败

时间:2019-06-13 08:39:12

标签: android android-intent uri android-permissions storage-access-framework

我正在尝试在示例活动中测试Storage Access Framework。 目标是获得用户选择的文件夹Uri的永久读写权限。

以下是该应用启动SAF文件选择器的方式:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, OPEN_DIRECTORY_REQUEST_CODE);

onActivityResult方法称为:

@Override
protected void onActivityResult(int requestCode,int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == OPEN_DIRECTORY_REQUEST_CODE) 
    {
        if (resultCode == Activity.RESULT_OK) 
        {
            int takeFlags = data.getFlags()& (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            ContentResolver resolver = this.getContentResolver();
            resolver.takePersistableUriPermission(data.getData(),takeFlags);
            updateDirectoryEntries(data.getData());


        } else 
          {
            // The user cancelled the request.
          }
    }
}

我得到了这个uri

"/tree/raw:/storage/emulated/0/Download/prova1"

并将其作为字符串。

下次应用运行以下方法称为:

public void consumeUri(String uriPath)
{
    ContentResolver contentResolver;
    contentResolver = this.getContentResolver();
    Uri uri;
    Uri docUri;
    uri=Uri.parse(uriPath);
    docUri= DocumentsContract.buildDocumentUriUsingTree(uri,
            DocumentsContract.getTreeDocumentId(uri)); //error here
}

我得到了这个堆栈跟踪:

java.lang.IllegalArgumentException: Invalid URI: /tree/raw:/storage/emulated/0/Download/prova1
    at android.provider.DocumentsContract.getTreeDocumentId(DocumentsContract.java:1023)
    at com.example.myapplication.MainActivity.consumeUri(MainActivity.java:123)
    at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:54)
    at android.view.View.performClick(View.java:6330)
    at android.view.View$PerformClick.run(View.java:24967)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6687)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)

我的代码怎么了?

1 个答案:

答案 0 :(得分:0)

保存Uri路径的正确方法似乎是通过

uri.toString();

Uri路径将具有以下形式:

content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ftest_folder