Using ACTION_OPEN_DOCUMENT with EXTRA_INITIAL_URI and a file:// Uri

816 Views Asked by At

Is it possible to use Intent.ACTION_OPEN_DOCUMENT with a file:// format Uri as an DocumentsContract.EXTRA_INITIAL_URI extra, to have DocumentsProvider start navigation in the file's location?

In my app I give user an option to use a custom settings file and when he chooses this option, am example default file is created at app's data folder (returned by getExternalFilesDir).

When selecting a custom file, I want the DocumentsProvider to open the folder where currently selected file is located with use of EXTRA_INITIAL_URI. There's no problem if some file was previously chosen with an ACTION_OPEN_DOCUMENT Intent, as returned Uri is of content:// format.

Problem exists before user selects the file for the first time and only Uri to created default custom file is available. File is created by use of File.createNewFile in directory returned by Context.getExternalFilesDir, and Uri is generated with use of Uri.fromFile(file), resulting in a file:// format Uri.

Here's a simple example code:

Creating custom file. Returns Uri like file:///storage/emulated/0/Android/data/com.example.testsapp/files/customFile.txt

fun createFile(context: Context): Uri {
        val appDir = context.getExternalFilesDir(null)
        val customFile = File(appDir, "customFile.txt")
        customFile.createNewFile()
        // writing to customFile via FileOutputStream(file)
        return Uri.fromFile(customFile)
    }

Letting user pick a custom file:

fun pickNewFile(fileUri: Uri) {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, fileUri)
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
        startActivityForResult(intent, FILE_PICKER_REQUEST_CODE)
    }

When fileUri is in file:// format, DocumentsProvider will won't open in file's directory, showing default directory instead. After user selects the new custom file, onActivityResult method will provide a new Uri, like content://com.android.externalstorage.documents/document/primary%3AAndroid%2Fdata%2Fcom.example.testsapp%2Ffiles%2FcustomFile.txt

When using this Uri with pickNewFile method, it will open on file's directory.

Is there a way to convert file:// type Uri to a content:// type Uri?

1

There are 1 best solutions below

2
On

No. Such conversion is not possible in Storage Access Framework as the content uri migh point to a storage file, files on flash drive or even a cloud provider

https://developer.android.com/guide/topics/providers/document-provider