Android try with resources no method found close()
Asked Answered
K

2

5

I am using android MediaMetaDataRetriever which implements AutoCloseable in an android application. I have the below code

try (final MediaMetadataRetriever retriever = new MediaMetadataRetriever()) {
    retriever.setDataSource(videoUri.getPath());
    return retriever.getFrameAtTime(10, getFrameOption());
}

minSDK > 21

but I am getting the following crash

No virtual method close()V in class Landroid/media/MediaMetadataRetriever; or its super classes (declaration of ‘android.media.MediaMetadataRetriever’ appears in /system/framework/framework.jar

how can this happen if MediaMetadataRetriever implements AutoCloseable

Komsa answered 28/8, 2020 at 10:22 Comment(2)
What API level are you using?Honour
I don't work on this project any more but I will as one of the developers who does to commentKomsa
B
5

how can this happen if MediaMetadataRetriever implements AutoCloseable.

Because MediaMetadataRetriever did not implement AutoCloseable until API 29. So on older platforms, the close() method does not exist, which is exactly what your crash is also saying.

On older platforms you have to (manually) call release() instead, which is what close() simply delegates to.

Unfortunately that means that you cannot use try-with-resources (or Kotlin's use) with MediaMetadataRetriever directly unless your minSdk is set to 29 or later.

Brewer answered 15/12, 2022 at 8:4 Comment(0)
N
5

I had the same problem, so I created my own subclass of MediaMetaDataRetriever in Kotlin:

class MyMediaMetadataRetriever : MediaMetadataRetriever(), AutoCloseable {

   override fun close() {
      release()
   }

}

Java (untested):

public class MyMediaMetadataRetriever extends MediaMetadataRetriever implements AutoCloseable {

   public MyMediaMetadataRetriever() {
      super();
   }

   @Override
   public void close() {
      release();
   }

}
Nectarine answered 12/12, 2020 at 16:41 Comment(2)
did you find out why?Komsa
Working well for Java, thanks.Biggin
B
5

how can this happen if MediaMetadataRetriever implements AutoCloseable.

Because MediaMetadataRetriever did not implement AutoCloseable until API 29. So on older platforms, the close() method does not exist, which is exactly what your crash is also saying.

On older platforms you have to (manually) call release() instead, which is what close() simply delegates to.

Unfortunately that means that you cannot use try-with-resources (or Kotlin's use) with MediaMetadataRetriever directly unless your minSdk is set to 29 or later.

Brewer answered 15/12, 2022 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.