197

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);
Timo Salomäki
  • 6,815
  • 3
  • 20
  • 37
Sushant Bhatnagar
  • 3,234
  • 9
  • 29
  • 39

27 Answers27

346

First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension(), like this:

// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}
Jared Burrows
  • 50,718
  • 22
  • 143
  • 180
Jens
  • 16,241
  • 4
  • 50
  • 50
  • 4
    thanks work for me and another solution of my problem is : public static String getMimeType(String path, Context context) { String extention = path.substring(path.lastIndexOf(".") ); String mimeTypeMap =MimeTypeMap.getFileExtensionFromUrl(extention); String mimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension(mimeTypeMap); return mimeType;} – Sushant Bhatnagar Dec 22 '11 at 07:23
  • 13
    And if the file has not the good extension? a person can make a .mp3 and it contains text – throrin19 Nov 25 '12 at 14:43
  • 2
    Then you'd need to actually open the file & check the magic number (depending on the format ofc) in the lead-in - this, however, also assumes that the person renaming txt-files to mp3 didn't just write `ID3` in the beginning of his text to mess with you even more. – Jens Nov 25 '12 at 14:49
  • @SushantBhatnagar you comment was helping but it need some improvment because i tried this but not working fine. – umerk44 Jan 14 '14 at 13:45
  • @Diederik what about mime type with codec type, for example: video/mp4;codecs="avc1.42001E, mp4a.40.2" (MimeTypeMap.getExtensionFromMimeType()))? YouTube return mime type with codec. I must use "video/mp4;codecs...".split(";",2)[0]. FLV is not registered (mime type starts with x-, in flv: x-flv), so MimeTypeMap for x- return null. http://en.wikipedia.org/wiki/Internet_media_type#Unregistered_x._tree (sorry for my english) – barwnikk Aug 16 '14 at 19:23
  • 1
    this is unreliable. It is terrible to depend on file extension and determine filetype from that. I can't believe such an important thing as mentioned by @throrin19 is being ignored. – Ankan-Zerob May 20 '15 at 23:21
  • 1
    If file has a unknown extension. Do method return `*/*`? –  Jul 07 '15 at 20:46
  • GPX is not recognized either. – Tim Autin Sep 02 '16 at 23:57
  • @TimAutin, method does not work with uppercase. Try modified one: http://stackoverflow.com/a/39923767/570168 – Tobias Oct 07 '16 at 18:34
  • 4
    If your have file path as /storage/emulated/0/Download/images (4).jpg and you ask for mimetype, it returns null. – Kalaiselvan Jan 31 '18 at 09:06
  • m3u8 is also returning null – Ranjith Kumar Jun 05 '18 at 07:41
  • it returns null .... @Diederik it shows 503 server error . your solution . http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils – Tarit Ray Jul 05 '18 at 16:41
  • Try this link instead: https://android.googlesource.com/platform/libcore/+/933e699897a15cc61e5641e6365f09f24e22b247/luni/src/main/java/libcore/net/MimeUtils.java – Diederik Jul 09 '18 at 14:52
  • 1
    I wasn't using a URL but just the file's full name, and the name contained spaces so the MimeTypeMap.getFileExtensionFromUrl(url) returned an empty String "". Therefore the type returned was null. So I used the following method to get the Extension: String extension = url.substring(url.lastIndexOf(".") + 1); – yalematta Dec 10 '18 at 16:46
193

Detect mime type of any file

public String getMimeType(Uri uri) {           
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = getAppContext().getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                .toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    }
    return mimeType;
}
palindrom
  • 13,280
  • 1
  • 16
  • 31
Hoa Le
  • 2,024
  • 1
  • 8
  • 6
  • 6
    This should be the correct answer. `toLowerCase()` did the trick. – Rajat Saxena Oct 24 '16 at 17:17
  • 3
    This is by far the best answer but it fails miserably if the file name has a special character, in my case an `apostrophe`! Eg. file name = `Don't go baby.mp3`. The `PatternMatcher` inside `MimeTypeMap.getFileExtensionFromUrl()` can not handle the file name and returns empty String; null comes out to be the mimetype String! – sud007 Jun 04 '18 at 18:41
  • There is a similar but error free solution below by `I. Shvedenenko` Worked for the issues I've pointed out above. But this answer was a pointer in correct direction. – sud007 Jun 04 '18 at 18:52
  • this code returns null with String "/storage/emulated/0/dcim/screenshots/screenshot_20190319-123828_ubl digital app.jpg" . – Abdul Apr 11 '19 at 07:38
  • 1
    @Abdul It is because that path does not have a Uri scheme. It should either start with `file://` or `content://`. – HB. Jan 22 '20 at 10:16
  • Why is the `ContentResolver` needed here? I thought file extension should be clear in the `Uri`, isn't it? – Minh Nghĩa Dec 15 '20 at 08:17
  • not working if actual image is gif but contains jpg extension – NehaK Mar 08 '21 at 09:16
36

The MimeTypeMap solution above returned null in my usage. This works, and is easier:

Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
String mime = cR.getType(uri);
Jeb
  • 581
  • 5
  • 7
26

Optimized version of Jens' answere with null-safety and fallback-type.

@NonNull
static String getMimeType(@NonNull File file) {
    String type = null;
    final String url = file.toString();
    final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    }
    if (type == null) {
        type = "image/*"; // fallback type. You might set it to */*
    }
    return type;
}

Important: getFileExtensionFromUrl() only works with lowercase!


Update (19.03.2018)

Bonus: Above methods as a less verbose Kotlin extension function:

fun File.getMimeType(fallback: String = "image/*"): String {
    return MimeTypeMap.getFileExtensionFromUrl(toString())
            ?.run { MimeTypeMap.getSingleton().getMimeTypeFromExtension(toLowerCase()) }
            ?: fallback // You might set it to */*
}
Igori S
  • 113
  • 8
Tobias
  • 6,533
  • 5
  • 59
  • 82
  • 1
    this worked. bit overly verbose for my liking though. – filthy_wizard Mar 16 '18 at 21:02
  • Of course this can be writter in a shorter manner. With Kotlin probably only two or three lines, however the foxus was on the null safety and `toLoverCase` part. – Tobias Mar 19 '18 at 21:08
  • @filthy_wizard, added an optimized version just for you ;-) – Tobias Mar 19 '18 at 21:21
  • As for me using getPath() method instead of toString() is more clear, and just path using kotlin property access syntax. – Leonid Jan 22 '20 at 13:18
16
File file = new File(path, name);

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    int index = file.getName().lastIndexOf('.')+1;
    String ext = file.getName().substring(index).toLowerCase();
    String type = mime.getMimeTypeFromExtension(ext);

    intent.setDataAndType(Uri.fromFile(file), type);
    try
    {
      context.startActivity(intent);
    }
    catch(ActivityNotFoundException ex)
    {
        ex.printStackTrace();

    }
umerk44
  • 2,691
  • 4
  • 20
  • 42
7

Pay super close attention to umerk44's solution above. getMimeTypeFromExtension invokes guessMimeTypeTypeFromExtension and is CASE SENSITIVE. I spent an afternoon on this then took a closer look - getMimeTypeFromExtension will return NULL if you pass it "JPG" whereas it will return "image/jpeg" if you pass it "jpg".

Andrew Myers
  • 2,567
  • 5
  • 26
  • 36
Mike Kogan
  • 268
  • 3
  • 10
6

Here is the solution which I used in my Android app:

public static String getMimeType(String url)
    {
        String extension = url.substring(url.lastIndexOf("."));
        String mimeTypeMap = MimeTypeMap.getFileExtensionFromUrl(extension);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeTypeMap);
        return mimeType;
    }
Mahendra Liya
  • 11,166
  • 10
  • 79
  • 105
  • 1
    url? A lot of url doesn't have extension. For example this page doesn't have extension. For url you should use new URL(url).openConnection().getRequestProperty("Content-type"); – barwnikk Aug 16 '14 at 19:13
5

Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.

/**
 *
 * @param is InputStream on start of file. Otherwise signature can not be defined.
 * @return int id of signature or -1, if unknown signature was found. See SIGNATURE_ID_(type) constants to
 *      identify signature by its id.
 * @throws IOException in cases of read errors.
 */
public static int getSignatureIdFromHeader(InputStream is) throws IOException {
    // read signature from head of source and compare with known signatures
    int signatureId = -1;
    int sigCount = SIGNATURES.length;
    int[] byteArray = new int[MAX_SIGNATURE_LENGTH];
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
        byteArray[i] = is.read();
        builder.append(Integer.toHexString(byteArray[i]));
    }
    if (DEBUG) {
        Log.d(TAG, "head bytes=" + builder.toString());
    }
    for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {

        // check each bytes with known signatures
        int bytes = byteArray[i];
        int lastSigId = -1;
        int coincidences = 0;

        for (int j = 0; j < sigCount; j++) {
            int[] sig = SIGNATURES[j];

            if (DEBUG) {
                Log.d(TAG, "compare" + i + ": " + Integer.toHexString(bytes) + " with " + sig[i]);
            }
            if (bytes == sig[i]) {
                lastSigId = j;
                coincidences++;
            }
        }

        // signature is unknown
        if (coincidences == 0) {
            break;
        }
        // if first bytes of signature is known we check signature for full coincidence
        if (coincidences == 1) {
            int[] sig = SIGNATURES[lastSigId];
            int sigLength = sig.length;
            boolean isSigKnown = true;
            for (; i < MAX_SIGNATURE_LENGTH && i < sigLength; i++) {
                bytes = byteArray[i];
                if (bytes != sig[i]) {
                    isSigKnown = false;
                    break;
                }
            }
            if (isSigKnown) {
                signatureId = lastSigId;
            }
            break;
        }
    }
    return signatureId;
}

signatureId is an index of signature in array of signatures. For example,

private static final int[] SIGNATURE_PNG = hexStringToIntArray("89504E470D0A1A0A");
private static final int[] SIGNATURE_JPEG = hexStringToIntArray("FFD8FF");
private static final int[] SIGNATURE_GIF = hexStringToIntArray("474946");

public static final int SIGNATURE_ID_JPEG = 0;
public static final int SIGNATURE_ID_PNG = 1;
public static final int SIGNATURE_ID_GIF = 2;
private static final int[][] SIGNATURES = new int[3][];

static {
    SIGNATURES[SIGNATURE_ID_JPEG] = SIGNATURE_JPEG;
    SIGNATURES[SIGNATURE_ID_PNG] = SIGNATURE_PNG;
    SIGNATURES[SIGNATURE_ID_GIF] = SIGNATURE_GIF;
}

Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.

It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.

Sergei Vasilenko
  • 2,183
  • 2
  • 25
  • 37
5

I tried to use standard methods to determine the mime type, but I cannot retain the file extension using MimeTypeMap.getFileExtensionFromUrl(uri.getPath()). This method returned me an empty string. So I made a non-trivial solution to retain the file extension.

Here is the method returning the file extension:

private String getExtension(String fileName){
    char[] arrayOfFilename = fileName.toCharArray();
    for(int i = arrayOfFilename.length-1; i > 0; i--){
        if(arrayOfFilename[i] == '.'){
            return fileName.substring(i+1, fileName.length());
        }
    }
    return "";
}

And having retained the file extension, it is possible to get mime type like below:

public String getMimeType(File file) {
    String mimeType = "";
    String extension = getExtension(file.getName());
    if (MimeTypeMap.getSingleton().hasExtension(extension)) {
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return mimeType;
}
klwire
  • 31
  • 7
  • Man, this nailed all the answers posted here on this problem! I had the same issue with all the Legacy classes. Issue was same as you've mentioned, `MimeTypeMap.getFileExtensionFromUrl` returned empty string for the Filenames which have invalid characters as per internal implementation of a `PatternMatcher`. This worked for me completely! Loved it, no issues so far! – sud007 Jun 04 '18 at 18:51
  • @I. Shvedenenko `String extension = file.getName().split("\\.")[1]` would also have worked, thereby, eliminating the getExtension() method. – Shahood ul Hassan Oct 31 '19 at 03:35
  • But the thing is, what if a wrong extension is used while creating the file? Should extension be the sole judge of mime type? – Shahood ul Hassan Oct 31 '19 at 03:36
  • Looks like you have problems with this solution if there's more than one `.` in the filename. In Kotlin, `val extension: String = file.name.split(".").last()` eliminates the need for `getExtension` and the more than one `.` problem. – lasec0203 Oct 22 '20 at 00:53
  • If you are still working on Java: file.getName().substring(file.getName().lastIndexOf(".")) – Carlos Cabello Ruiz Feb 26 '21 at 13:19
3

its works for me and flexible both for content and file

public static String getMimeType(Context context, Uri uri) {
    String extension;

    //Check uri format to avoid null
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        //If scheme is a content
        final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

    }

    return extension;
}
Yohanes AI
  • 2,632
  • 6
  • 42
  • 75
2

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/

2

For Xamarin Android (From @HoaLe's answer above)

public String getMimeType(Uri uri) {
    String mimeType = null;
    if (uri.Scheme.Equals(ContentResolver.SchemeContent))
    {
        ContentResolver cr = Application.Context.ContentResolver;
        mimeType = cr.GetType(uri);
    }
    else
    {
        String fileExtension = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString());
        mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(
        fileExtension.ToLower());
    }
    return mimeType;
}
Curiousity
  • 1,405
  • 3
  • 20
  • 42
1
get file object....
File file = new File(filePath);

then....pass as a parameter to...

getMimeType(file);

...here is 


public String getMimeType(File file) {
        String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()).toLowerCase());
        if (mimetype == null) {
            return "*/*";
        }
        return mimetype;///return the mimeType
    }
Nilesh
  • 953
  • 13
  • 20
1

While from asset/file(Note that few cases missing from the MimeTypeMap).

private String getMimeType(String path) {
    if (null == path) return "*/*";

    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }

    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        return "text/javascript";
    } else if (extension.equals("woff")) {
        return "application/x-font-woff";
    } else {
        // TODO
        // anyting missing from the map (http://www.sitepoint.com/web-foundations/mime-types-complete-list/)
        // reference: http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils
    }

    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

While use ContentResolver

contentResolver.getType(uri)

While http/https request

    try {
        HttpURLConnection conn = httpClient.open(new URL(uri.toString()));
        conn.setDoInput(false);
        conn.setRequestMethod("HEAD");
        return conn.getHeaderField("Content-Type");
    } catch (IOException e) {
    }
WCG
  • 71
  • 4
1
// This will return the mimeType. 
// for eg. xyz.png it will return image/png. 
// here uri is the file that we were picked using intent from ext/internal storage.
private String getMimeType(Uri uri) {
   // This class provides applications access to the content model.  
   ContentResolver contentResolver = getContentResolver();

   // getType(Uri url)-Return the MIME type of the given content URL. 
   return contentResolver.getType(uri);
}
iamdhariot
  • 11
  • 1
  • 4
1

I faced similar problem. So far I know result may different for different names, so finally came to this solution.

public String getMimeType(String filePath) {
    String type = null;
    String extension = null;
    int i = filePath.lastIndexOf('.');
    if (i > 0)
        extension = filePath.substring(i+1);
    if (extension != null)
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    return type;
}  
Ashish Sahu
  • 1,398
  • 16
  • 22
1

I don't realize why MimeTypeMap.getFileExtensionFromUrl() has problems with spaces and some other characters, that returns "", but I just wrote this method to change the file name to an admit-able one. It's just playing with Strings. However, It kind of works. Through the method, the spaces existing in the file name is turned into a desirable character (which, here, is "x") via replaceAll(" ", "x") and other unsuitable characters are turned into a suitable one via URLEncoder. so the usage (according to the codes presented in the question and the selected answer) should be something like getMimeType(reviseUrl(url)).

private String reviseUrl(String url) {

        String revisedUrl = "";
        int fileNameBeginning = url.lastIndexOf("/");
        int fileNameEnding = url.lastIndexOf(".");

        String cutFileNameFromUrl = url.substring(fileNameBeginning + 1, fileNameEnding).replaceAll(" ", "x");

        revisedUrl = url.
                substring(0, fileNameBeginning + 1) +
                java.net.URLEncoder.encode(cutFileNameFromUrl) +
                url.substring(fileNameEnding, url.length());

        return revisedUrl;
    }
elyar abad
  • 730
  • 1
  • 7
  • 24
1

EDIT

I created a small library for this. But the underlying code is nearly the same.

It's available on GitHub

MimeMagic-Android

Solution September 2020

Using Kotlin

fun File.getMimeType(context: Context): String? {
    if (this.isDirectory) {
        return null
    }

    fun fallbackMimeType(uri: Uri): String? {
        return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            context.contentResolver.getType(uri)
        } else {
            val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.getDefault()))
        }
    }

    fun catchUrlMimeType(): String? {
        val uri = Uri.fromFile(this)

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val path = Paths.get(uri.toString())
            try {
                Files.probeContentType(path) ?: fallbackMimeType(uri)
            } catch (ignored: IOException) {
                fallbackMimeType(uri)
            }
        } else {
            fallbackMimeType(uri)
        }
    }

    val stream = this.inputStream()
    return try {
        URLConnection.guessContentTypeFromStream(stream) ?: catchUrlMimeType()
    } catch (ignored: IOException) {
        catchUrlMimeType()
    } finally {
        stream.close()
    }
}

That seems like the best option as it combines the previous answers.

First it tries to get the type using URLConnection.guessContentTypeFromStream but if this fails or returns null it tries to get the mimetype on Android O and above using

java.nio.file.Files
java.nio.file.Paths

Otherwise if the Android Version is below O or the method fails it returns the type using ContentResolver and MimeTypeMap

DatLag
  • 92
  • 5
0

The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.

Luis Barragan
  • 46
  • 1
  • 5
0

mime from local file:

String url = file.getAbsolutePath();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mime = fileNameMap.getContentTypeFor("file://"+url);
Flinbor
  • 3,097
  • 1
  • 20
  • 25
0

you have multiple choice to get extension of file:like: 1-String filename = uri.getLastPathSegment(); see this link

2-you can use this code also

 filePath .substring(filePath.lastIndexOf(".")+1);

but this not good aproch. 3-if you have URI of file then use this Code

String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE };

4-if you have URL then use this code:

 public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) { 


  type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }

return type;
}

enjoy your code:)

John smith
  • 1,671
  • 14
  • 27
0
// new processing the mime type out of Uri which may return null in some cases
String mimeType = getContentResolver().getType(uri);
// old processing the mime type out of path using the extension part if new way returned null
if (mimeType == null){mimeType URLConnection.guessContentTypeFromName(path);}
YEH
  • 354
  • 4
  • 17
0
public static String getFileType(Uri file)
{
    try
    {
        if (file.getScheme().equals(ContentResolver.SCHEME_CONTENT))
            return subStringFromLastMark(SystemMaster.getContentResolver().getType(file), "/");
        else
            return MimeTypeMap.getFileExtensionFromUrl(file.toString()).toLowerCase();
    }
    catch(Exception e)
    {
        return null;
    }
}

public static String getMimeType(Uri file)
{
    try
    {
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileType(file));
    }
    catch(Exception e)
    {
        return null;
    }
}

public static String subStringFromLastMark(String str,String mark)
{
    int l = str.lastIndexOf(mark);
    int end = str.length();
    if(l == -1)
        return str;

    return str.substring(l + 1, end);
}
Ali Bagheri
  • 1,866
  • 19
  • 21
0

Has also return null value in my case path was

/storage/emulated/0/Music/01 - Ghost on the Dance Floor.mp3

as work around use

val url = inUrl.replace(" ","")

so method looks like

@JvmStatic
    fun getMimeType(inUrl: String?): String {
        if (inUrl == null) return ""

        val url = inUrl.replace(" ","")
        var type: String? = null

        val extension = MimeTypeMap.getFileExtensionFromUrl(url)
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())
        }

        if(type ==null){
            val cR = WifiTalkie.getApplicationContext().contentResolver
            type = cR.getType(Uri.parse(url))
        }

        if (type == null) {
            type = "*/*" // fallback method_type. You might set it to */*
        }
        return type
    }

as result it return success result:

audio/mpeg

Hope it helps anybody

Serg Burlaka
  • 1,867
  • 19
  • 31
0

None of the answers here are perfect. Here is an answer combining the best elements of all the top answers:

public final class FileUtil {

    // By default, Android doesn't provide support for JSON
    public static final String MIME_TYPE_JSON = "application/json";

    @Nullable
    public static String getMimeType(@NonNull Context context, @NonNull Uri uri) {

        String mimeType = null;
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            ContentResolver cr = context.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = getExtension(uri.toString());

            if(fileExtension == null){
                return null;
            }

            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());

            if(mimeType == null){
                // Handle the misc file extensions
                return handleMiscFileExtensions(fileExtension);
            }
        }
        return mimeType;
    }

    @Nullable
    private static String getExtension(@Nullable String fileName){

        if(fileName == null || TextUtils.isEmpty(fileName)){
            return null;
        }

        char[] arrayOfFilename = fileName.toCharArray();
        for(int i = arrayOfFilename.length-1; i > 0; i--){
            if(arrayOfFilename[i] == '.'){
                return fileName.substring(i+1, fileName.length());
            }
        }
        return null;
    }

    @Nullable
    private static String handleMiscFileExtensions(@NonNull String extension){

        if(extension.equals("json")){
            return MIME_TYPE_JSON;
        }
        else{
            return null;
        }
    }
}
Manish Kumar Sharma
  • 11,112
  • 7
  • 50
  • 86
0
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
                        File file = new File(filePatch); 
                        Uri uris = Uri.fromFile(file);
                        String mimetype = null;
                        if 
(uris.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                            ContentResolver cr = 
getApplicationContext().getContentResolver();
                            mimetype = cr.getType(uris);
                        } else {
                            String fileExtension = 
MimeTypeMap.getFileExtensionFromUrl(uris.toString());
mimetype =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
                        }
rm8x
  • 7,154
  • 1
  • 10
  • 17
0

I consider the easiest way is to refer to this Resource file: https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/net/android.mime.types

Andrey Novikov
  • 5,413
  • 5
  • 27
  • 50