Android在WebView中使用H5来调用本地相机相册的方法

最近在做一个项目需求是在Android原生的Activity中嵌套一个WebView来做混合开发,之前也做过这样的开发方式,一般都是

纯H5的逻辑使用,但是这次使用的是H5来调用本地的相机相册,下面坑来了:

1:首先Android原生和H5的交互的集成问题。

2:H5中调用本地的相机相册和视频拍摄是调用不起来的,需要原生自己调用。

3:WebView在使用过程中会出现一系列问题。

首先解决第一个问题:

原生和H5交互的问题中为了方便一般使用第三方库,GitHub上有开源库,其中选择了一个Star比较多的https://github.com/lzyzsd/JsBridge,但是我在集成后出现了一个问题是H5发消息给原生,原生能接收到,但是原生发消息给H5的时候H5死活接收不到,这个问题调试了很久都没有调试成功,最后选择放弃了,使用了另外一种集成方式,也是使用的这个开源库,但是是以lib的形式集成到本地的,把lib包集成到本地项目中(资源下载):

   1:在app下的build.gradle的dependencies闭包中添加如下依赖

    compile project(':library')

   2:如果你的包中有多个依赖还要在defaultConfig闭包中添加如下依赖,不然打包会报错:

    defaultConfig {
          ................
        multiDexEnabled true
       }

   3:在项目的最外层settings.gradle中加入

   include ':app', ':library'

   4:OK集成完毕

然后解决第二个问题:

在原生代码中实例化WebView后做如下配置:

        WebSettings webSettings = webView.getSettings();
        
        webSettings.setDomStorageEnabled(true);//设置适应Html5 //重点是这个设置
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setAllowContentAccess(true); // 是否可访问Content Provider的资源,默认值 true
        webSettings.setAllowFileAccess(true);    // 是否可访问本地文件,默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件,默认值 false
        webSettings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
        webSettings.setAllowUniversalAccessFromFileURLs(false);

        webView.loadUrl(url);
        webView.setWebViewClient(new BridgeWebViewClient(webView){
            @Override
            public void onPageFinished(WebView view, String url) {
                if (mode == SingleH5.IEO || mode == SingleH5.H5APPLY || mode == SingleH5.APPMARKET) {
                    String title = view.getTitle();
                    if (!TextUtils.isEmpty(title)) {
                        tvName.setText(title);
                    }
                }
                super.onPageFinished(view, url);
            }
        });
//        webView.setDefaultHandler(new DefaultHandler());
        webView.setWebChromeClient(new MyChromeWebClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根,其中pb是WebView上面的进度条
                if (newProgress == 100) {
                    pb.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    pb.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pb.setProgress(newProgress);//设置进度值
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
               
            }
        });

2:我们重新写的MyChromeWebClient为:

//自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
    public class MyChromeWebClient extends WebChromeClient {
        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            Log.d("openFileChoose", "openFileChoose(ValueCallback<Uri> uploadMsg)");
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            Log.d("openFileChoose", "openFileChoose( ValueCallback uploadMsg, String acceptType )");
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            Log.d("openFileChoose", "openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            Log.d("openFileChoose", "onShowFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadCallbackAboveL = filePathCallback;
            checkSelfPermission();
//            takePhoto();
            return true;
        }
    }

    /**
     * 拍照或选择相册
     */
    private void takePhoto() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(ItWaterTableActivity.this);
        alertDialog.setTitle("选择");
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setItems(new CharSequence[]{"相机", "相册"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
                            imageUri = Uri.fromFile(fileUri);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                imageUri = FileProvider.getUriForFile(ItWaterTableActivity.this, "com.ib.android.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                            }else {
                                imageUri = Uri.fromFile(fileUri);
                            }
                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(intent,PHOTO_REQUEST);
                        } else {
                            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                            i.addCategory(Intent.CATEGORY_OPENABLE);
                            i.setType("image/*");
                            ItWaterTableActivity.this.startActivityForResult(Intent.createChooser(i, "File Browser"), PHOTO_REQUEST);
                        }
                    }
                });
        alertDialog.show();
    }
    /**
     * 点击取消的回调
     */
    private class ReOnCancelListener implements
            DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
        }
    }

3:在onActivityResult中接收如下:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PHOTO_REQUEST) {
        if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (mUploadCallbackAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, data);
        } else if (mUploadMessage != null) {
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
    if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) {
        return;
    }
    Uri[] results = null;
    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            results = new Uri[]{imageUri};
        } else {
            String dataString = data.getDataString();
            ClipData clipData = data.getClipData();
            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }

            if (dataString != null)
                results = new Uri[]{Uri.parse(dataString)};
        }
    }
    mUploadCallbackAboveL.onReceiveValue(results);
    mUploadCallbackAboveL = null;
}

OK

现在解决第三个问题:

  问题一:权限问题:

调用相机之后,文件回调不了,其实根本就是没有回调.这个时候你要去检查你的webview的Settings了关键代码,是否给足了权限;

       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);
其中settings.setDomStorageEnabled(true);这个方法当时我没加,崩了一次;
 

问题二:WebChromeClient的openFileChooser()只调用了一次
首先了解为什么这个方法只调用了一次,看这篇博客就可
Android开发深入理解WebChromeClient之onShowFileChooser或openFileChooser使用说明
看了他基本你就了解怎么回事了,

简单来说就是每次调用onShowFileChooser或openFileChooser都要设置一个回调;不管你是不是选择了照片,如果没有就回传一个null,在本文上述代码中已经做了回调监听处理,所以这个问题就简单的解决了。

问题三:怎么区分是要调用相机是需要拍照还是录视频
1,这个时候你就要看WebViewClient的 shouldOverrideUrlLoading()方法了,我是通过拦截url来判断url里面是拍照还是录制视频来加一个flag,然后这样你调用你的相机的时候就可以分别处理了
2,另外如果实在拿不到这个flag,可以通过html的input标签来accept类型判断
在哪里拿呢

 //  5.0+ acceptType
   public boolean onShowFileChooser(WebView webView,
    ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            String[] acceptTypes = fileChooserParams.getAcceptTypes();
}

  // For Android 3.0+acceptType
    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
    }

这样就可以拿到是accept进行调用了,在本文中我的操作是在原生中调用了一个弹窗,然后让用户选择是拍照还是选择图片。

问题四:android 7.0的FileProvider的坑
看洪阳大佬的这篇博客基本就了解了
Android 7.0 行为变更 通过FileProvider在应用间共享文件吧

发布了116 篇原创文章 · 获赞 165 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_42618969/article/details/100579480