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
}
Based on...
how can I determine which application(s) can handle a file, if any?
I think what you want is PackageManager.queryIntentActivities where you create an intent based on the target file and then read the returned list.