意图ACTION_OPEN_DOCUMENT_TREE似乎没有返回驱动

时间:2017-05-25 16:30:36

标签: android android-file android-fileprovider

我试图从连接到Google Pixel的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/...,它似乎不是Android文件系统中的真实路径(通过adb shell验证)。如何使用此uri查询便携式存储设备的内容?我尝试使用here给出的答案,但链接的函数返回null

1 个答案:

答案 0 :(得分:3)

你正在获得树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