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

前端 未结 1 617
心在旅途
心在旅途 2020-12-29 17:15

I\'m trying to read files from a USB storage device connected to my Google Pixel. I\'m currently using this method to select the path of the drive so I can query it for its

相关标签:
1条回答
  • 2020-12-29 17:46

    You are getting tree Uri. So you need to Add below code to get files from 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");
    
            }
    

    For the query the contents, you can use below code.

    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
        }
    

    You can check Google sample code: https://github.com/googlesamples/android-DirectorySelection/blob/master/Application/src/main/java/com/example/android/directoryselection/DirectorySelectionFragment.java#L150

    0 讨论(0)
提交回复
热议问题