Set MIME-type of a file on Android

Asked

Viewed 244 times

4

I need to dynamically figure 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.

1 answer

4


Information extracted and mined from of this answer in the international SO

If you do not have direct access to the file (such as being available via FTP or HTTP), you can try to rescue MIME-type by file extension. The class android.webkit.MimeTypeMap has exactly what is needed for 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 the ContentResolver.getType.

public String getMimeType(Uri uri) {
    ContentResolver cr = getContentResolver();
    return cr.getType(uri);
}

In the documentation of getType there’s no mention of how he makes the discovery. Maybe it’s by extension, maybe by magic numbers of the file, which is a much more reliable detection than by the simple extension.

How to find out if the access is direct? Well, we can see in which Scheme content is found. If 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());
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.