H5与原生App交互,需要调用相机或者麦克风时,需要手机端处理权限申请逻辑,在webView的WebChromeClient中处理回调:
webView.webChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest?) {
val resources = request?.resources ?: return
val permissions = mutableListOf<String>()
resources.forEach { permission ->
if (permission == PermissionRequest.RESOURCE_VIDEO_CAPTURE) {
permissions.add(Manifest.permission.CAMERA)
} else if (permission == PermissionRequest.RESOURCE_AUDIO_CAPTURE) {
permissions.add(Manifest.permission.RECORD_AUDIO)
permissions.add(Manifest.permission.MODIFY_AUDIO_SETTINGS) //注意,一定要申请这个权限,同时在manifest里声明
}
}
if (permissions.isEmpty()) return
//此处处理权限申请,替换成自己的方法
PermissionX.init(this@WebViewActivity).permissions(permissions).request { allGranted, grantedList, deniedList ->
if (allGranted) {
//权限申请通过,告诉H5
request.grant(resources)
} else {
//权限被拒绝
request.deny()
}
}
}
}