Android. How to determine the type of media file in onActivityResult()?
Asked Answered
S

2

4

I get media file from Gallery.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*,video/*,audio/*");
            startActivityForResult(Intent.createChooser(intent, "Select Media"), CameraUtils.REQUEST_GALLERY);

How to determine the type of media file in onActivityResult()?

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case CameraUtils.REQUEST_GALLERY:
                Uri uri = data.getData();
                //what type of media file?
                break;
        }
    }
}
Shift answered 18/12, 2014 at 17:26 Comment(0)
V
22

Try this:

ContentResolver cr = this.getContentResolver();
String mime = cr.getType(uri);
Vo answered 18/12, 2014 at 17:41 Comment(0)
E
0

Just for reference, in Kotlin we can create an extension function for this.

fun Activity.getMimeType(uri:Uri?):String?{
    this.let {
        val cr: ContentResolver = it.contentResolver
        if (uri == null) return  null
        return cr.getType(uri)?:null
    }
    
}

Feel free to replace nulls with empty String or something. but this works fines!

Emaciated answered 4/2, 2021 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.