kotlin
fun hasAudioPermissions(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_MEDIA_AUDIO
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
this,
Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
} else {
ContextCompat.checkSelfPermission(
this,
Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
}
}
private fun requestAudioPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissionLauncher.launch(
arrayOf(
Manifest.permission.READ_MEDIA_AUDIO,
Manifest.permission.RECORD_AUDIO
)
)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissionLauncher.launch(
arrayOf(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE
)
)
} else {
// 对于安卓6.0以下的版本,不需要动态请求权限
// 这些版本在安装时就会请求所有权限
}
}
// 注册权限请求
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
// 检查权限结果
val readMediaAudioGranted = permissions[Manifest.permission.READ_MEDIA_AUDIO] ?: false
val recordAudioGranted = permissions[Manifest.permission.RECORD_AUDIO] ?: false
val readExternalStorageGranted = permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
if ((readMediaAudioGranted && recordAudioGranted) || (recordAudioGranted && readExternalStorageGranted)) {
// 权限已授予
} else {
// 权限被拒绝
this.showToast("没有权限,播放失败")
}
}
亲测有效。
播放的时候也需要检测: