ClassCastException: MediaMetadataRetriever 不能转换为 AutoCloseable

问题描述

我尝试将 MediaMetadataRetriever 与 Kotlin use 结合使用:

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

但它在 Android 6 Marshmallow (23 API) 上给了我一个错误

java.lang.classCastException: android.media.MediaMetadataRetriever 不能强制转换为 java.lang.AutoCloseable

为什么会这样?

解决方法

MediaMetadataRetriever 实现 AutoCloseable since API level 29

,

Android 是开源项目,您可以查看每个版本的源代码。好像不久前开始实现 AutoClosable

API 28:

public class MediaMetadataRetriever
{

API 30

public class MediaMetadataRetriever implements AutoCloseable {