I am developing an application which lists files in a folder (in a ListView). When the user clicks on one of the items, if it is a file, then I would like to launch an activity that can handle it, if any, or display some kind of error message if there is none.
How can I do that? Not the whole thing, of course, but how can I determine which application(s) can handle a file, if any.
First, you will need to determine the MIME type of the file. You can do this using MimeTypeMap:
MimeTypeMap map = MimeTypeMap.getSingleton();
String extension = map.getFileExtensionFromUrl(url); // url is the url/location of your file
String type = map.getMimeTypeFromExtension(extension);
Then once you know the MIME type, you can create an intent for that type:
Intent intent = new Intent();
intent.setType(type);
Finally, you want to check if any activities can resolve the intent with that type. This can be done via the PackageManager:
PackageManager manager = getPackageManager(); // I'm assuming this is done from within an activity. This a Context method.
List<ResolveInfo> resolvers = manager.queryIntentActivities(intent, 0);
if (resolvers.isEmpty()) {
// display error
} else {
// launch the intent. You will also want to set the data based on the uri of your file
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With