ClassCastException: MediaMetadataRetriever cannot be cast to AutoCloseable

1k Views Asked by At

I tried to use MediaMetadataRetriever with Kotlin use:

MediaMetadataRetriever().apply {
    setDataSource(context, uri)
}.use {
    ...
}

But it gives me an error on Android 6 Marshmallow (23 API):

java.lang.ClassCastException: android.media.MediaMetadataRetriever cannot be cast to java.lang.AutoCloseable

Why so?

3

There are 3 best solutions below

1
sdex On BEST ANSWER

MediaMetadataRetriever implements AutoCloseable since API level 29.

1
Mikhail On

Android is open source project, you can check the sources for every revision. Seems it started to implement AutoClosable not long ago

API 28:

public class MediaMetadataRetriever
{

API 30

public class MediaMetadataRetriever implements AutoCloseable {
0
Rubén Viguera On

When you say you are using "Kotlin" use method I assume you are referring to the one in androidx.core.content.res package at androidx.core:core-ktx library.

But this one does not use AutoCloseable interface at all. Instead MediaMetadataRetriever class also provides of a use method since API 29, as user sdex states in his answer, which you might be using by mistake.

On the contrary, use method from androidx is backwards compatible.

Then, you just have to import the following:

import androidx.core.content.res.use