H5调用android相机拍照

起因:H5页面通过openAPP协议唤起客户端,调用系统照相机,并完成拍照图片上传,然后将图片URL回传给H5;
后来发现不如让H5侧直接唤起系统照相机,完成拍照后,进行图片上传。

一、H5侧实现唤起照相机 ,参考自Capturing an Image from the User

相关代码如下:

<input type="file" accept="image/*" capture>
<input type="file" accept="image/*" capture="user">
<input type="file" accept="image/*" capture="environment">

二、APP实现

1. WebSetting权限

 	WebSettings settings = webView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源,默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件,默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件,默认值 false
        settings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
        settings.setAllowUniversalAccessFromFileURLs(false);
        //开启JavaScript支持
        settings.setJavaScriptEnabled(true);
        // 支持缩放
        settings.setSupportZoom(true);

2. WebChromeClient方法复写

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(CustomWebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            if(fileChooserParams != null && fileChooserParams.isCaptureEnabled()){// 判断是否使用相机
                openCamera();
            }else {
                openImageChooserActivity();
            }
            return true;
        }

3. 调用系统相机

权限注册,以及动态申请权限不在本文中,注:android 6.0以后,相机权限需要动态申请。

   //用于保存拍照图片的uri
    private Uri mCameraUri;
 
    // 用于保存图片的文件路径,Android 10以下使用图片路径访问图片
    private String mCameraImagePath;
 
    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
 
    /**
     * 调起相机拍照
     */
    private void openCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;
 
            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
 
                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限,通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                    } else {
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }
 
            mCameraUri = photoUri;
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }
 
    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
           return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }
 
    /**
     * 创建保存图片的文件
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }

4. 接收照片

   @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CAMERA_REQUEST_CODE){
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            if (uploadMessageAboveL != null) {
                if (Activity.RESULT_OK == resultCode) {
                    uploadMessageAboveL.onReceiveValue(new Uri[]{mCameraUri});
                }else {
                    uploadMessageAboveL.onReceiveValue(null);
                }
                uploadMessageAboveL = null;
            } else if (uploadMessage != null) {
                if (Activity.RESULT_OK == resultCode) {
                    uploadMessage.onReceiveValue(mCameraUri);
                }else {
                    uploadMessage.onReceiveValue(null);
                }
                uploadMessage = null;
            }
        }
        } 

5. 调用系统相机适配

android 7.0需要配置文件共享.

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

在res目录下创建文件夹xml ,放置一个文件file_paths.xml(文件名可以随便取),配置需要共享的文件目录,也就是拍照图片保存的目录。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <!-- 这个是保存拍照图片的路径,必须配置。 -->
        <external-files-path
            name="images"
            path="Pictures" />
    </paths>
</resources>

参考文章列表:
[Android 调用相机拍照,适配到Android 10]{https://blog.csdn.net/weixin_45365889/article/details/100977510}
[深坑之Webview,解决H5调用android相机拍照和录像]{https://blog.csdn.net/villa_mou/article/details/78728417}
[android-WebView支持input file启用相机/选取照片]{https://www.cnblogs.com/maggieq8324/p/11414769.html}

原文地址:https://www.cnblogs.com/sishuiliuyun/p/15036271.html