简体   繁体   中英

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"))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM