Android 意图操作\u打开\u文档\u树似乎没有返回真正的驱动路径

Android 意图操作\u打开\u文档\u树似乎没有返回真正的驱动路径,android,android-file,android-fileprovider,Android,Android File,Android Fileprovider,我正在尝试从连接到谷歌像素的USB存储设备读取文件。我目前正在使用此方法选择驱动器的路径,以便查询其内容 private static final String TAG = "MainActivity"; private static final int REQUEST_CHOOSE_DRIVE = 1; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.o

我正在尝试从连接到谷歌像素的USB存储设备读取文件。我目前正在使用此方法选择驱动器的路径,以便查询其内容

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/。。。在通过adb外壳验证的Android文件系统中,这似乎不是一条真正的路径。如何使用此uri查询便携式存储设备的内容?我尝试使用给定的答案,但链接函数返回null。

您得到的是树Uri。因此,您需要添加以下代码以从树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
    }
您可以查看谷歌示例代码:

谢谢,所以我正在尝试使用Bitmap Bitmap=BitmapFactory.decodeFilefilePath;但我不知道文件路径是什么。我试着做file.getUri.getPath,但它说没有这样的文件或directory@Carpetfizz:使用ContentResolver和openInputStream获取Uri标识的内容的InputStream。然后,使用decodeStream而不是decodeFile。此外,DocumentFile使遍历文档树变得更简单。是的,先生,这是一种更好的方法,而不是解码文件@地毯泡沫:您可以使用contentResolver.openInputStreamuri获取内容的InputStream。请确保您的Uri是位图的有效源。再次感谢您的两个答案,他们做了我希望他们做的事情!有没有办法读取队列中的文件?我希望能够一个接一个地将文件排出来,而不是将它们读入内存Ay我在SD卡上有文件如何获取此文件的DocumentFile以便删除它?