I am using Android ACTION_CREATE_DOCUMENT
to select a location to save a PDF file.
After getting the uri
and writing to the file (as done in the code below), I want to show a Snackbar
with the action set to opening the location of the file.
To be clear I don't want to open the file itself, but to help user locate the file using the file explorer app. Is there a "developer.android.com" recommended way to do this? The current code is as follows.
private void getSaveLocation() {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "MyFile.pdf");
startActivityForResult(intent, MY_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK || data == null || data.getData() == null) return;
Uri uri = data.getData();
OutputStream out = getContext().getContentResolver().openOutputStream(uri);
// write the pdf to out
try {
out.close();
showSnackbar(uri);
} catch (IOException e) {
e.printStackTrace();
}
}
void showSnackbar(Uri uri) {
Snackbar snackbar = Snackbar.make(getView(), "Saved to MyFile.pdf", Snackbar.LENGTH_LONG);
snackbar.setAction("Locate file", new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// NEED TO SETUP THE INTENT CORRECTLY USING uri
activity.startActivity(intent);
}
});
snackbar.show();
}
Is there a "developer.android.com" recommended way to do this?
No.
First, there is no standard "open a file explorer on a particular location" Intent
action.
Second, there is no requirement that ACTION_OPEN_DOCUMENT
be used to open a document that is part of something that can be explored. The user can use it to access documents in other things (encrypted containers, cloud storage, etc.) that may not necessarily be accessible by a file manager.