5

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.

Gallal
  • 4,267
  • 6
  • 38
  • 61
  • There are many other similar posts about this but nothing this specific and nothing that answers my question, so please carefully read the other posts before flagging this as a duplicate. – Gallal Jun 14 '11 at 01:48

2 Answers2

7

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
}
Noel
  • 7,350
  • 1
  • 36
  • 26
  • I tried this, and it works fine with some extensions like 'pdf' and 'doc', but it gives me a long non-sense list when I use 'JPG'; it shows system tools such as GPS as an applcaition that can handle 'JPG'. ANy other suggestions? – Gallal Jun 14 '11 at 22:05
  • 1
    There is also a getPreferredActivities() method in the PackageManager which you can leverage to determine if there is a preferred app of handling a specific MIME type but otherwise, that is the intended android behaviour. – Noel Jun 14 '11 at 23:11
0

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.

Andrew White
  • 52,720
  • 19
  • 113
  • 137