Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launching an Activity based on a file in android

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.

like image 556
Gallal Avatar asked Jun 14 '11 01:06

Gallal


1 Answers

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
}
like image 142
Noel Avatar answered Sep 24 '22 19:09

Noel