I want to let the user of my app choose a file, then the app open this file. For opening the file, I need its uri. In the official documentation https://developer.android.com/training/basics/intents/result#launch I see this simple example :
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
Called with :
mGetContent.launch("image/*");
That allows to open the selected file. Exactly what I need.
But I'd like to define an initial directory, called EXTRA_INITIAL_URI, but this can be set with a putExtra like this :
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI,uri);
The problem is that there is no intent in this kind of implementation. So my question is : is it possible to define a EXTRA_INITIAL_URI , if yes how ?
Thanks a lot.
GetContent
, and theACTION_GET_CONTENT
that it is named after doesn't supportEXTRA_INITIAL_URI
at all: the list of intents it does support include:which is why it isn't a parameter on that particular Activity Result Contract.
You'll note that
OpenDocumentTree
specifically states:Which maps to setting the
EXTRA_INITIAL_URI
for that Activity Result contract, so you can use that contract directly if you are trying to select a folder.For the other two,
CreateDocument
andOpenDocument
, both specifically state:Which means you'd extend that contract to set the initial Uri.
For example, if you wanted to pass in the initial Uri as a constructor parameter to the contract, you'd write the class as
Which you'd then use in place of
GetContent
:The guide to creating custom contracts talks more about writing type safe contracts if, for example, you wanted to instead have to pass the Uri and a mime type to
launch
, you could write your own custom contract that doesn't extendOpenDocument
at all, but instead just uses the same underlying Intent extras that you want.