Java – Android uses intent to open external directories

Android uses intent to open external directories… here is a solution to the problem.

Android uses intent to open external directories

There is no direct or explicit way to imply the intent to open a folder/directory in Android.
Specifically, I want to open getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) here.

I

tried these, but they only open a FileManager application, not the directory I want:

val directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
val uri = Uri.parse(directory.path)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.setDataAndType(uri, "*/*")
startActivity(Intent.createChooser(openIntent, "Open Folder"))

Another example:

val directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
val uri = Uri.parse(directory.path)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri, "resource/folder")
startActivity(Intent.createChooser(openIntent, "Open Folder"))

Solution

Open the “THE” download folder

If you want to open the download folder, you need to use DownloadManager.ACTION_VIEW_DOWNLOADS, like this:

Intent downloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(downloadIntent);

There is no need to use the mime type resource/folder because Android does not have an official folder mime type, so you may produce some errors in some devices. Your device does not appear to support this MIME type. You need to use the code above because it just passes the official folder you want to access to Intent.


EDIT: For other custom directories, I don’t think you can just pass a path to the intent like that one. I don’t think there’s a reliable way to open a folder in Android.


Use FileProvider (test

).

EDIT: If you are using FileProvider, try not just parsing URIs, you should use getUriForFile( ). Like this:

val dir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val intent = new Intent(Intent.ACTION_VIEW)
val mydir = getUriForFile(context, "paste_your_authority", dir)
intent.setDataAndType(mydir, "resource/folder")
startActivity(intent);

Or instead of using resources/folders, use:

DocumentsContract.Document.MIME_TYPE_DIR

The moral of the story:

There is no standard way to open a file. Every device is different, and the code above is not guaranteed to work on every device.

Related Problems and Solutions