Intent ACTION_OPEN_DOCUMENT_TREE 似乎 return 不是真正的驱动路径

Intent ACTION_OPEN_DOCUMENT_TREE doesn't seem to return a real path to drive

我正在尝试从连接到我的 Google Pixel 的 USB 存储设备读取文件。我目前正在使用此方法 select 驱动器的路径,以便我可以查询它的内容

private static final String TAG = "MainActivity";
private static final int REQUEST_CHOOSE_DRIVE = 1;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.text);

    Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

    startActivityForResult(i, REQUEST_CHOOSE_DRIVE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CHOOSE_DRIVE) {

        Uri uri = data.getData();

    }
}

但是,Uri 看起来像 /tree/...,这似乎不是 Android 文件系统中的真实路径(通过 adb shell 验证)。我如何使用这个 uri 查询便携式存储设备的内容?我尝试使用给出的答案 但链接函数 returns null.

您正在获取树 Uri。所以你需要添加下面的代码来从 Tree Uri 中获取文件。

        DocumentFile documentFile = DocumentFile.fromTreeUri(this, uri);
        for (DocumentFile file : documentFile.listFiles()) {

            if(file.isDirectory()){ // if it is sub directory
                // Do stuff with sub directory
            }else{
                // Do stuff with normal file
            }

           Log.d("Uri->",file.getUri() + "\n");

        }

查询内容,可以使用下面的代码。

ContentResolver contentResolver = getActivity().getContentResolver();
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri,
            DocumentsContract.getTreeDocumentId(uri));
    Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri,
            DocumentsContract.getTreeDocumentId(uri));
Cursor docCursor = contentResolver.query(docUri, new String[]{
            Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE}, null, null, null);
    try {
        while (docCursor.moveToNext()) {
            Log.d(TAG, "found doc =" + docCursor.getString(0) + ", mime=" + docCursor
                    .getString(1));

        }
    } finally {
        // close cursor
    }

您可以查看Google示例代码: https://github.com/googlesamples/android-DirectorySelection/blob/master/Application/src/main/java/com/example/android/directoryselection/DirectorySelectionFragment.java#L150