问题描述: 在 Android 11 上,使用 WebView 加载网页时,相机无法工作,并且会出现以下错误提示:不支持 mime 类型 image/vnd.android.heic。
解决方法:
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
// 在 Activity 的 onActivityResult 方法中添加以下代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
// 处理相机返回的数据
// ...
}
}
// 在 WebViewClient 的 onPageStarted 方法中添加以下代码
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (url.contains("camera")) { // 替换为相机操作的 URL
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
// 在 WebViewClient 的 shouldOverrideUrlLoading 方法中添加以下代码
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
String url = request.getUrl().toString();
if (url.endsWith(".heic")) {
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("heic");
if (mimeType != null && mimeType.equals("image/vnd.android.heic")) {
String convertedUrl = convertHeicToJpeg(url); // 将 .heic 格式图片转换为 .jpeg 格式
if (convertedUrl != null) {
view.loadUrl(convertedUrl);
return true;
}
}
}
}
return super.shouldOverrideUrlLoading(view, request);
}
// 将 .heic 格式图片转换为 .jpeg 格式的方法
private String convertHeicToJpeg(String heicUrl) {
// 实现转换逻辑,将 .heic 格式图片转换为 .jpeg 格式
// 返回 .jpeg 格式图片的 URL
return jpegUrl;
}
以上代码示例中的 REQUEST_CAMERA 是一个自定义的整数常量,用于标识相机请求。您可以根据自己的需要进行调整。
希望以上解决方法能够帮助您解决问题。