The correct mimeType to open the file

I am trying to open File using Intent , but Android does not open the correct application for the file type.

Using the following code, each file - pdf, images, everything - is opened using a music application:

 Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.fromFile(file)); startActivity(i); 

When I manually specify mimeType, the correct application opens - in this case, the image viewer.

 i.setDataAndType(Uri.fromFile(file), "image/*"); 

Is there a way to get Android to open the right application instead of manually setting the type judging from the file extension?

+4
source share
2 answers

It depends on other applications. If they set their intent filters, including meme information, file extension information, or both. So my recommendation is that you cannot rely on other applications, so the best option is to provide as much information as possible when launching the intent, including the MIME type.

+1
source

You can do something like this:

 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.fromFile(file)); intent.setType(FileHelper.getMimeType(file)); startActivity(intent); 

Here is the (relevant part) of my helper class to get mimeType from a file .

The key is to use MimeTypeMap

 public class FileHelper { public static String getMimeType(File file) { return getMimeType(file.getName()); } public static String getMimeType(String fileName) { String extension = getExtension(fileName); if (extension == null) return null; return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } public static String getExtension(File file) { return getExtension(file.getName()); } public static String getExtension(String fileName) { int extensionDelimiter = fileName.lastIndexOf("."); if (extensionDelimiter == -1) return null; return fileName.substring(extensionDelimiter + 1, fileName.length()); } } 

Hope this helps.

+1
source

All Articles