准备工作
声明权限:
<uses-permission android:name="android.permission.CAMERA" />
使用前动态申请相机权限。
Android7.0以上需要 声明FileProvider (https://www.jianshu.com/p/47fcd7873f39)
开始
val CAPTURE_REQUEST = 123
var mFilePathCallback: ValueCallback<Array<Uri>>? = null //webview内部回调
var captureUri: Uri? = null //使用该uri接收系统返回的图片/视频
fun file2Uri(file: File): Uri {
//Android 7.0以上需要使用fileprovider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val authority = application.packageName + ".provider"
return FileProvider.getUriForFile(Utils.getApp(), authority, file)
} else {
return Uri.fromFile(file)
}
}
mWebview.webChromeClient = object : WebChromeClient() {
/**
* 复写该方法
*/
override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
mFilePathCallback = filePathCallback
if (fileChooserParams?.acceptTypes?.isNotEmpty() == true) {
val mipmap = fileChooserParams.acceptTypes[0]
when (mipmap) {
"image/*" -> {
val file = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "imageCapture${System.currentTimeMillis()}.jpg")
///文件路径 storage/emulated/0/Android/data/包名/files/Pictures/imageCapture1563956535105.jpg
captureUri = file2Uri(file)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(intent, CAPTURE_REQUEST)
return true
}
"video/*" -> {
val file = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "videoCapture${System.currentTimeMillis()}.mp4")
///文件路径 storage/emulated/0/Android/data/包名/files/Pictures/videoCapture1563956535105.mp4
captureUri = file2Uri(file)
val intent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(intent, CAPTURE_REQUEST)
return true
}
}
}
return super.onShowFileChooser(webView, filePathCallback, fileChooserParams)
}
}
接收返回结果
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAPTURE_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
mFilePathCallback?.onReceiveValue(arrayOf(captureUri)) //给回调设置数据
} else
mFilePathCallback?.onReceiveValue(arrayOf()) //给回调设置空数据
}
}
网友评论