My app has a feature that exports GPS data in txt format into a shared folder (now accessed with getExternalStorageDirectory
), and I have to switch it to Scoped Storage (API 30).
(As information, the app is the open source GPS Logger for Android.)
In the future I would let the users choose the folder to be used for the exportation, using:
public void openDirectory(Uri uriToLoad) {
// Choose a directory using the system's file picker.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, your-request-code);
}
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == your-request-code && resultCode == Activity.RESULT_OK) {
// The result data contains a URI for the directory that the user selected.
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
// Perform operations on the document using its URI.
}
}
}
This way my app will gain access to the selected folder.
How can I create a text file into that folder and write data using a BufferedWriter
?
I know that maybe I can use something like:
...
Uri fileUri = // Something related to the previous uri, but I cannot find the solution
OutputStream outputStream = getContentResolver().openOutputStream(fileUri, "rw");
txtBW = new BufferedWriter(new OutputStreamWriter(outputStream));
...
but I found nothing that works.
DocumentFile
is Google's somewhat clunky solution for navigating through document trees. The recipe for what you want should be:Uri
that you got for your tree and wrap it in aDocumentFile
usingDocumentFile.fromTreeUri()
createFile()
on thatDocumentFile
, supplying a filename or other display name, which will give you aDocumentFile
representing that documentgetUri()
on the document'sDocumentFile
to get aUri
representing the documentopenOutputStream()
on aContentResolver
to write your desired content to thatUri
Note that if you need long-term access to this tree, be sure to call
takePersistableUriPermission()
on aContentResolver
, passing in theUri
for the document tree. That should give you access to the tree and all documents inside of it.