Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.
I created a function for it
public static String getMimeType(File file, Context context)
{
Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));
return type;
}
but when i call it, it returns null.
File file = new File(filePath);
String fileType=CommonFunctions.getMimeType(file, context);
MimeTypeMap
may not recognize some file extensions like flv,mpeg,3gpp,cpp. So you need to think how to expand the MimeTypeMap for maintaining your code. Here is such an example.http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils
Plus, here is a complete list of mime types
http: //www.sitepoint.com/web-foundations/mime-types-complete-list/
First and foremost, you should consider calling
MimeTypeMap#getMimeTypeFromExtension()
, like this:The MimeTypeMap solution above returned null in my usage. This works, and is easier:
For Xamarin Android (From @HoaLe's answer above)