Cannot set the initial location of documents navigator using Storage Access Framework (SAF)

前端 未结 2 642
一生所求
一生所求 2021-01-12 16:48

The documentation says \"Callers can set a document URI through EXTRA_INITIAL_URI to indicate the initial location of documents navigator.\"

But it won

相关标签:
2条回答
  • 2021-01-12 17:14

    From DocumentsContract.EXTRA_INITIAL_URI:

    Location should specify a document URI or a tree URI with document ID. If this URI identifies a non-directory, document navigator will attempt to use the parent of the document as the initial location.

    As far as I'm aware

    • You cannot specify a starting location using an arbitrary URI, e.g. Uri.fromFile, it needs to originate from a DocumentsProvider
    • You cannot specify a starting location on API 25 and below

    Assuming uri was retrieved from Intent.ACTION_OPEN_DOCUMENT_TREE:

    DocumentFile file = DocumentFile.fromTreeUri(context, uri);
    intent.putExtra(EXTRA_INITIAL_URI, file.getUri());
    
    0 讨论(0)
  • 2021-01-12 17:21

    I think you need a content URI like "content:/some/uri" for this to work.

    The following is based on the answer in question MediaStore - Uri to query all types of files (media and non-media):

    String getFileContentUri(ContentResolver contentResolver, File file){
        String filePath = file.getAbsolutePath();
        Uri uri = MediaStore.Files.getContentUri("external");
    
        String[] projection = {MediaStore.Files.FileColumns.DATA};
    
        String selection = MediaStore.Files.FileColumns.DATA+"=? ";
        String[] selectionArgs = new String[] { filePath };
    
        String sortOrder = null;
        Cursor fileCursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
        if(fileCursor != null && fileCursor.moveToFirst()){
            int columnIndex = fileCursor.getColumnIndex(projection[0]);
            filePath = fileCursor.getString(columnIndex);
            fileCursor.close();
            return filePath;
        }
    
        return null;
    }
    

    Also you probably need to request the permission android.permission.READ_EXTERNAL_STORAGE.

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