javaandroidtry-with-resources

Android try with resources no method found close()


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


Solution

  • 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.