Let Android open a file in an app that can handle the file, like opening a PDF in Adobe Reader. Or opening an image in your photo viewer.

Determine the mimetype by file extension:

public static String getMimeType(String filename) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(filename);

    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

 

Let Android open the file by finding the right app for it. It throws an unchecked ActivityNotFoundException if there could not be found an app that can handle this file.

public static void openIntent(Context context, File file, String mimeType) {
	String mimetype = mimeType;
	Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
	myIntent.setDataAndType(Uri.fromFile(file), mimetype);
	try {
		context.startActivity(myIntent);
	} catch(ActivityNotFoundException e) {
		Toast.makeText(context, "No app found for this file type.",
				Toast.LENGTH_SHORT).show();
	}
}

 

Use it like this:

//The file you want to open
File file = new File("/somedir/somefile.png");

//Get the mimetype of the file
String mimeType = getMimeType(file.getName());

//Open the file in a new Activity
openIntent(getContext(), file, mimeType);