MediaStore Uri 上的 ContentResolver.query() 仅适用于 Android API 31+ - MediaStore.getMediaUri() BUG?

问题描述 投票:0回答:1

我检查了以下代码,它仅适用于 API 31+,对于较低版本,

Cursor
null

private fun getMediaInfo(context: Context, uri: Uri): Long? {
    try {
        context.contentResolver.query(
            uri,
            arrayOf(
                MediaStore.MediaColumns.DURATION
            ),
            null, null, null
        )?.use { cursor ->
            var duration: Long? = null
            if (cursor.moveToFirst()) {
                val durationColumnId =
                    cursor.getColumnIndex(MediaStore.MediaColumns.DURATION)
                if (durationColumnId != -1) {
                    duration = cursor.getLongOrNull(durationColumnId)
                }
                return duration
            }
        }
    } catch (e: Throwable) {
        e.printStackTrace()
    }
    return null
}

对于较低的 API 版本如何使用

MediaStore

附注使用

MediaStore.getMediaUri(context, uri)
(Android API 29+)后,我从 DocumentProvider Uri 获取 Media Uri
content://com.android.externalstorage.documents/tree/primary%3AMovies/document/primary%3AMovies%2FVoiceRecorder%2FVoice%202024.02.19%2021_45_51.m4a

变成:

content://media/external_primary/file/60

但它仅适用于 Android API 31+,对于 29、30

Cursor
null

我也尝试了

MediaStore.MediaColumns.BITRATE
,这次我得到了例外

java.lang.IllegalArgumentException: Invalid column bitrate

在 Android 30 上

Cursor
null

对于 Android 31+

BITRATE
DURATION
都可以正常工作

android mediastore android-contentresolver
1个回答
0
投票

这对我的应用程序来说效果很好

public Uri get_audio_media_uri(){
Uri uri_to_use = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    uri_to_use = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
    uri_to_use = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
return uri_to_use;

}

© www.soinside.com 2019 - 2024. All rights reserved.