I need to dynamically find out what the MIME-type of a file is. Initially, I only need to identify videos, but I intend to use this to identify HTML pages, photos, PDF etc.
I need to dynamically find out what the MIME-type of a file is. Initially, I only need to identify videos, but I intend to use this to identify HTML pages, photos, PDF etc.
Information extracted and mined from this answer in the international OS
If you do not have direct access to the file (such as being available via FTP or HTTP), you can try to redeem the MIME-type for the file extension. The android.webkit.MimeTypeMap
class has exactly what it takes to do this. See the method getMimeTypeFromExtension
.
public String getMimeType(Uri uri) {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}
If you have local access, you can also try using ContentResolver.getType
.
public String getMimeType(Uri uri) {
ContentResolver cr = getContentResolver();
return cr.getType(uri);
}
In the documentation for getType
there is no mention of how it does the discovery. Maybe it's by extension, perhaps by magic numbers of the file, which is a much more reliable detection of the which by simple extension.
How to find out if the access is direct? Well, we can see in which scheme the content is. If you are SCHEME_CONTENT
, SCHEME_ANDROID_RESOURCE
or SCHEME_FILE
", then it is safe to consider as local:
public boolean contentSchemeLocal(Uri uri) {
String scheme = uri.getScheme();
return scheme.equals(ContentResolver.SCHEME_FILE) ||
scheme.equals(ContentResolver.SCHEME_ANDROID_RESOURCE) ||
scheme.equals(ContentResolver.SCHEME_CONTENT);
}
public String getMimeType(Uri uri) {
if (contentSchemaLocal(uri)) {
ContentResolver cr = getContentResolver();
return cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}
}