Reza Bigdeli
Reza Bigdeli

Reputation: 1172

Android open an external directory using an intent

There is not a straightforward or a clear way to make an implicit intent to open a folder/directory in Android. Specifically here I want to open getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).

I tried these ones but they will just open a FileManager app, 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"))

Upvotes: 3

Views: 2289

Answers (1)

Gaurav Mall
Gaurav Mall

Reputation: 2412

Opening 'THE' Downloads folder

If you want to open the downloads 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);

No need to use mime type resource/folder as Android doesn't have an official folder mime type, so you could produce some errors in some devices. Your device seems not to support that mime type. You need to use the code above, as it just passes to the intent the official folder you want to go to.


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


Using FileProvider(Test)

Edit: Try instead of just parsing the Uri, if you are using FileProvider, which 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 resource/folder, use:

DocumentsContract.Document.MIME_TYPE_DIR

Moral of the story:

There is no standard way of opening files. Every device is different and the code above is not guaranteed to work in every single device.

Upvotes: 3

Related Questions