1.第一步需要进行基础的权限请求,比如用Rxpermission、PermissionsDispatcher、easypermissions进行初步检查
这个检查注意针对原生安卓系统和部分手机进行初步请求
2.部分手机上进行第一步的时候返回了已存在权限,但是实际上没有权限,就需要进行第二部的具体判断了,话不多说,直接上代码
A.拍照权限
class CameraPermissionHelper {
companion object {
//是否有拍照权限
fun hasCameraPermission(): Boolean {
return try {
//targetSdkVersion低于23,使用异常捕捉相机权限
val camera = Camera.open()
camera.release()
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
}
B.录音权限
class AudioPermissionHelper {
companion object {
//是否有录音权限
fun hasRecordPermission(): Boolean {
val minBufferSize = AudioRecord.getMinBufferSize(
44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT
)
val audioRecord: AudioRecord? = null
try {
audioRecord = AudioRecord(
MediaRecorder.AudioSource.MIC, 44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize
)
} catch (e: Exception) {
e.printStackTrace()
}
if (audioRecord == null) {
return false
}
try {
// 开始录音
audioRecord.startRecording()
} catch (e: Exception) {
//可能情况一
audioRecord.release()
LogUtils.e("MMAudioRecorderPanel hasRecordPermission", e)
}
// 检测是否在录音中,6.0以下会返回此状态
if (audioRecord.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
//可能情况二
try {
audioRecord.stop()
audioRecord.release()
} catch (e: Exception) {
LogUtils.e("MMAudioRecorderPanel hasRecordPermission", e)
}
return false
}
val bufferSizeInBytes = 1024
val audioData = ByteArray(bufferSizeInBytes)
var readSize = 0
// 正在录音
readSize = audioRecord.read(audioData, 0, bufferSizeInBytes)
if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize <= 0) {
return false
}
try {
audioRecord.stop()
audioRecord.release()
} catch (e: Exception) {
LogUtils.e("MMAudioRecorderPanel hasRecordPermission", e)
}
return true
}
}
}
网友评论