webview之加载H5界面无法调用手机本地图库

2024-09-06 16:18

本文主要是介绍webview之加载H5界面无法调用手机本地图库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

webview加载H5页面,如果H5界面需要调用手机的本地图库

首先在此祝各位大佬远离BUG

  • 比如我们在开发中会遇到这样的场景,需要加载一个H5界面,这个界面里面可能有用户上传头像这个功能,但是当你怎么点击上传图片的时候它都无响应。但是你把这个H5用手机浏览器打开,会发现他可以正常调用手机本地的图库,对于此类问题,我分两种情况讲
  • Acvtivity里面用webview去加载 H5界面。
  • fragment里面用webview去加载 H5界面。

Acvtivity里面用webview去加载 H5界面。首先要重新设置myChromeViewClient和myWebViewClinet,会根据不用的系统调用不用的回调,2.0 3.0 4.0 5.0+,需要注意的是回调在onActivityResult方法里面。

解决方案上代码

首先需要定义成员变量:

private UploadHandler mUploadHandler;
private ValueCallback<Uri[]> mUploadMessageForAndroid5;
public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;
private MyChromeViewClient myChromeViewClient =new MyChromeViewClient();

然后拿到webview控件对其设置:

webview.setWebChromeClient(myChromeViewClient);
webview.setWebViewClient(myWebViewClinet);

重写onActivityResult方法,因为设置myChromeViewClient和myWebViewClinet,会根据不用的系统调用不用的回调,2.0
3.0 4.0 5.0+,而各种回调的执行都在onActivityResult里面:

@Overrideprotected void onActivityResult(int requestCode, int resultCode,Intent intent) {if (requestCode == Controller.FILE_SELECTED) {// Chose a file from the file picker.if (mUploadHandler != null) {mUploadHandler.onResult(resultCode, intent);}} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {if (null == mUploadMessageForAndroid5)return;Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null: intent.getData();System.out.println("-----------界面执行了回调"+(result == null));if (result != null) {mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });} else {mUploadMessageForAndroid5.onReceiveValue(new Uri[] {});}mUploadMessageForAndroid5 = null;}super.onActivityResult(requestCode, resultCode, intent);}

然后将一下代码复制到你的activity里面

class MyDownloadListener implements DownloadListener {@Overridepublic void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype, long contentLength) {// TODO Auto-generated method stub}}/*** 有几个类要说明下:* * MyChromeViewClient* 继承WebChromeClient重写了几个关键方法。其中有三个重载方法openFileChooser,用来兼容不同的Andorid版本* ,以防出现NoSuchMethodError异常。* 另外一个类UploadHandler,起到一个解耦合作用,它相当于WebChromeClient和Web网页端的一个搬运工兼职翻译* ,解析网页端传递给WebChromeClient的动作* ,然后将onActivityResult接收用户选择的文件传递给司机ValueCallback* 。WebChromeClient提供了一个Web网页端和客户端交互的通道,而UploadHandler就是用来搬砖的~。* UploadHandler有个很重要的成员变量:ValueCallback<Uri>* mUploadMessage。ValueCallback是WebView留下来的一个回调* ,就像是WebView的司机一样,当WebChromeClient和UploadHandler合作将文件选择后* ,ValueCallback开始将文件给WebView,告诉WebView开始干活了,砖头已经运回来了,你可以盖房子了。*/class MyChromeViewClient extends WebChromeClient {@Overridepublic void onCloseWindow(WebView window) {WebViewCustomer.this.finish();super.onCloseWindow(window);}public void onProgressChanged(WebView view, final int progress) {}@Overridepublic boolean onJsAlert(WebView view, String url, String message,final JsResult result) {new AlertDialog.Builder(WebViewCustomer.this).setTitle("提示信息").setMessage(message).setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int which) {result.confirm();}}).setCancelable(false).create().show();return true;}@Overridepublic boolean onJsConfirm(WebView view, String url, String message,final JsResult result) {new AlertDialog.Builder(WebViewCustomer.this).setTitle("提示信息").setMessage(message).setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int which) {result.confirm();}}).setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int which) {result.cancel();}}).setCancelable(false).create().show();return true;}// Android 2.xpublic void openFileChooser(ValueCallback<Uri> uploadMsg) {openFileChooser(uploadMsg, "");}// Android 3.0public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType) {openFileChooser(uploadMsg, "", "filesystem");}// Android 4.1public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType, String capture) {mUploadHandler = new UploadHandler(new Controller());mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);}// For Android 5.0+public boolean onShowFileChooser(WebView webView,ValueCallback<Uri[]> filePathCallback,WebChromeClient.FileChooserParams fileChooserParams) {openFileChooserImplForAndroid5(filePathCallback);return true;}}private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {mUploadMessageForAndroid5 = uploadMsg;Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);contentSelectionIntent.setType("image/*");Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择图片");System.out.println("-----------调用");startActivityForResult(chooserIntent,FILECHOOSER_RESULTCODE_FOR_ANDROID_5);}class MyWebViewClinet extends WebViewClient {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {return true;}}// copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.javaclass UploadHandler {/** The Object used to inform the WebView of the file to upload.*/private ValueCallback<Uri> mUploadMessage;private String mCameraFilePath;private boolean mHandled;private boolean mCaughtActivityNotFoundException;private Controller mController;public UploadHandler(Controller controller) {mController = controller;}public String getFilePath() {return mCameraFilePath;}boolean handled() {return mHandled;}public void onResult(int resultCode, Intent intent) {if (resultCode == Activity.RESULT_CANCELED&& mCaughtActivityNotFoundException) {// Couldn't resolve an activity, we are going to try again so// skip// this result.mCaughtActivityNotFoundException = false;return;}Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null: intent.getData();// As we ask the camera to save the result of the user taking// a picture, the camera application does not return anything other// than RESULT_OK. So we need to check whether the file we expected// was written to disk in the in the case that we// did not get an intent returned but did get a RESULT_OK. If it// was,// we assume that this result has came back from the camera.if (result == null && intent == null&& resultCode == Activity.RESULT_OK) {File cameraFile = new File(mCameraFilePath);if (cameraFile.exists()) {result = Uri.fromFile(cameraFile);// Broadcast to the media scanner that we have a new photo// so it will be added into the gallery for the user.mController.getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,result));}}mUploadMessage.onReceiveValue(result);mHandled = true;mCaughtActivityNotFoundException = false;}public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType, String capture) {final String imageMimeType = "image/*";final String videoMimeType = "video/*";final String audioMimeType = "audio/*";final String mediaSourceKey = "capture";final String mediaSourceValueCamera = "camera";final String mediaSourceValueFileSystem = "filesystem";final String mediaSourceValueCamcorder = "camcorder";final String mediaSourceValueMicrophone = "microphone";// According to the spec, media source can be 'filesystem' or// 'camera' or 'camcorder'// or 'microphone' and the default value should be 'filesystem'.String mediaSource = mediaSourceValueFileSystem;if (mUploadMessage != null) {// Already a file picker operation in progress.return;}mUploadMessage = uploadMsg;// Parse the accept type.String params[] = acceptType.split(";");String mimeType = params[0];if (capture.length() > 0) {mediaSource = capture;}if (capture.equals(mediaSourceValueFileSystem)) {// To maintain backwards compatibility with the previous// implementation// of the media capture API, if the value of the 'capture'// attribute is// "filesystem", we should examine the accept-type for a MIME// type that// may specify a different capture value.for (String p : params) {String[] keyValue = p.split("=");if (keyValue.length == 2) {// Process key=value parameters.if (mediaSourceKey.equals(keyValue[0])) {mediaSource = keyValue[1];}}}}// Ensure it is not still set from a previous upload.mCameraFilePath = null;if (mimeType.equals(imageMimeType)) {if (mediaSource.equals(mediaSourceValueCamera)) {// Specified 'image/*' and requested the camera, so go ahead// and launch the// camera directly.startActivity(createCameraIntent());return;} else {// Specified just 'image/*', capture=filesystem, or an// invalid capture parameter.// In all these cases we show a traditional picker filetered// on accept type// so launch an intent for both the Camera and image/*// OPENABLE.Intent chooser = createChooserIntent(createCameraIntent());chooser.putExtra(Intent.EXTRA_INTENT,createOpenableIntent(imageMimeType));startActivity(chooser);return;}} else if (mimeType.equals(videoMimeType)) {if (mediaSource.equals(mediaSourceValueCamcorder)) {// Specified 'video/*' and requested the camcorder, so go// ahead and launch the// camcorder directly.startActivity(createCamcorderIntent());return;} else {// Specified just 'video/*', capture=filesystem or an// invalid capture parameter.// In all these cases we show an intent for the traditional// file picker, filtered// on accept type so launch an intent for both camcorder and// video/* OPENABLE.Intent chooser = createChooserIntent(createCamcorderIntent());chooser.putExtra(Intent.EXTRA_INTENT,createOpenableIntent(videoMimeType));startActivity(chooser);return;}} else if (mimeType.equals(audioMimeType)) {if (mediaSource.equals(mediaSourceValueMicrophone)) {// Specified 'audio/*' and requested microphone, so go ahead// and launch the sound// recorder.startActivity(createSoundRecorderIntent());return;} else {// Specified just 'audio/*', capture=filesystem of an// invalid capture parameter.// In all these cases so go ahead and launch an intent for// both the sound// recorder and audio/* OPENABLE.Intent chooser = createChooserIntent(createSoundRecorderIntent());chooser.putExtra(Intent.EXTRA_INTENT,createOpenableIntent(audioMimeType));startActivity(chooser);return;}}// No special handling based on the accept type was necessary, so// trigger the default// file upload chooser.startActivity(createDefaultOpenableIntent());}private void startActivity(Intent intent) {try {mController.getActivity().startActivityForResult(intent,Controller.FILE_SELECTED);} catch (ActivityNotFoundException e) {// No installed app was able to handle the intent that// we sent, so fallback to the default file upload control.try {mCaughtActivityNotFoundException = true;mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),Controller.FILE_SELECTED);} catch (ActivityNotFoundException e2) {// Nothing can return us a file, so file upload is// effectively disabled.Toast.makeText(mController.getActivity(),"File uploads are disabled.", Toast.LENGTH_LONG).show();}}}private Intent createDefaultOpenableIntent() {// Create and return a chooser with the default OPENABLE// actions including the camera, camcorder and sound// recorder where available.Intent i = new Intent(Intent.ACTION_GET_CONTENT);i.addCategory(Intent.CATEGORY_OPENABLE);i.setType("*/*");Intent chooser = createChooserIntent(createCameraIntent(),createCamcorderIntent(), createSoundRecorderIntent());chooser.putExtra(Intent.EXTRA_INTENT, i);return chooser;}private Intent createChooserIntent(Intent... intents) {Intent chooser = new Intent(Intent.ACTION_CHOOSER);chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);chooser.putExtra(Intent.EXTRA_TITLE, "Choose file for upload");return chooser;}private Intent createOpenableIntent(String type) {Intent i = new Intent(Intent.ACTION_GET_CONTENT);i.addCategory(Intent.CATEGORY_OPENABLE);i.setType(type);return i;}private Intent createCameraIntent() {Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);File cameraDataDir = new File(externalDataDir.getAbsolutePath()+ File.separator + "browser-photos");cameraDataDir.mkdirs();mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator+ System.currentTimeMillis() + ".jpg";cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(mCameraFilePath)));return cameraIntent;}private Intent createCamcorderIntent() {return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);}private Intent createSoundRecorderIntent() {return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);}}class Controller {final static int FILE_SELECTED = 4;Activity getActivity() {return WebViewCustomer.this;}}

以上代码就可以解决我们在webview加载H5界面的时候无法调用手机本地图库的问题。网上也有很多,和这个类似或者差不多的,我只能说我亲测这个是没有问题的。

如果你的webview是在fragment里面,那你用了我以上的方法就很难受,会骂我在网上随便百度一个就发播客,我也曾经这样过。

我们现在说一下在fragment是怎么回事。在activity里面的时候说过,解决这个问题需要我们设置myChromeViewClient和myWebViewClinet,会根据不用的系统调用不用的回调,2.0 3.0 4.0 5.0+,需要注意的是回调在onActivityResult方法里面,但是fragment的回调是在fragment所在的activity的onActivityResult方法里面,所以fragment里面需要实现的话,需要在他所在的activity的onActivityResult方法里面设置监听或者发送广播,然后调用fragment里面onActivityResult这个方法执行。(可以将这个方法重命名,只要执行就可以)。也可以将fragment里面的这个方法做成静态方法,直接去调用,然后将数据传递进行执行就可以。这里可能有些新手或者刚入门的小伙伴在开发中遇到这个问题,还是希望我不要这么多废话,直接给代码和解决方案:(在这我先说一下根本原因:就是图库选择的图片再回传的时候,传给了fragment所在的activity)

那么首先:
在fragment所在的activity里面重写

@Overrideprotected void onActivityResult(int arg0, int arg1, Intent arg2) {super.onActivityResult(arg0, arg1, arg2);if(arg0 == 2 || arg0 == 4){Intent intent = new Intent("pictureCallback"); intent.putExtra("requestCode", arg0);  intent.putExtra("resultCode", arg1);  if(arg2 == null){intent.putExtra("webviewintent", ""); }else{intent.putExtra("webviewintent", arg2.getData().toString()); }sendBroadcast(intent);}}

有人会问了,你这个2和4是什么鬼。我这样告诉你,我也不知道是什么鬼。但是我在fragment所在的activity里面的onActivityResult方法里面监听,每当我点击打开图片这个功能,都会在activity的onActivityResult方法里面获取到这两个数字,我觉得应该是每次activity去打开其他activity都有标识的,可能这个2和4就是。我试了很多次都是这样。如果你们用着不行,那建议你们在这个方法里面打印一下log日志,看一下你们的arg0是多少。但是我觉得应该是我这个没错。你们现在应该很清楚,我用的是广播这种方法。有人可能会吐槽,但是我觉得还不错。
我们继续,后面只需要在fragment里面去接收一下这个广播就可以了。就能执行上面的那些方法

在fragment里面定义变量

WebViewPictureCallback myBroadcastReceiver = null;

注册广播

myBroadcastReceiver = new WebViewPictureCallback();
IntentFilter filter = new IntentFilter("pictureCallback"); 
((MainActivity)getActivity()).registerReceiver(myBroadcastReceiver, filter);

自定义广播接收者

    public class WebViewPictureCallback extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {if(intent != null&& intent.getAction().equals("pictureCallback")&& getResultCode() == Activity.RESULT_OK){Uri uri = null;if("".equals(intent.getStringExtra("webviewintent"))){uri = null;}else{uri = Uri.parse((intent.getStringExtra("webviewintent")));}gallery(intent.getIntExtra("requestCode", 0),intent.getIntExtra("resultCode", 0),uri);}}}

大家看到了gallery方法,其实就是前面activity里面说的onActivityResult方法,只是重新起了个方法名,然后去调用

    public void gallery(int requestCode, int resultCode, Uri data) {if (requestCode == Controller.FILE_SELECTED) {// Chose a file from the file picker.if (mUploadHandler != null) {mUploadHandler.onResult(resultCode, data);}} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {if (null == mUploadMessageForAndroid5){return;}Uri result = (data == null || resultCode != Activity.RESULT_OK) ? null: data;if (result != null) {mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });} else {mUploadMessageForAndroid5.onReceiveValue(new Uri[] {});}mUploadMessageForAndroid5 = null;}}

所以总结一下,在activity里面使用web view调用不了本地图库的方法我已经给出了,在fragment里面只是fragmnet没法响应回调,即打开图库,之后在图库里面选择的图片值传回来,fragment本身无法接收到,所以就多了一个中间环节,在fragment所在的activity里面先接受,然后把这个值不管你是想用我前面说的方法,还是我用的广播。在fragment里面去接收一下图库返回的值,然后其他的就还是按照上面的方法执行的。
以上是webview加载H5无法打开手机本地图库的问题。本来还有很多webview开发过程中的坑,发现一篇博客没法给大家说完,所以我之后还会写一些其他的webview开发遇到的坑。如果各位大佬有什么问题欢迎吐槽,如果对你有帮助,解决了问题。请帮忙顶一下。
谢谢

这篇关于webview之加载H5界面无法调用手机本地图库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1142502

相关文章

在java中如何将inputStream对象转换为File对象(不生成本地文件)

《在java中如何将inputStream对象转换为File对象(不生成本地文件)》:本文主要介绍在java中如何将inputStream对象转换为File对象(不生成本地文件),具有很好的参考价... 目录需求说明问题解决总结需求说明在后端中通过POI生成Excel文件流,将输出流(outputStre

SpringBoot配置Ollama实现本地部署DeepSeek

《SpringBoot配置Ollama实现本地部署DeepSeek》本文主要介绍了在本地环境中使用Ollama配置DeepSeek模型,并在IntelliJIDEA中创建一个Sprin... 目录前言详细步骤一、本地配置DeepSeek二、SpringBoot项目调用本地DeepSeek前言随着人工智能技

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

Python实现自动化接收与处理手机验证码

《Python实现自动化接收与处理手机验证码》在移动互联网时代,短信验证码已成为身份验证、账号注册等环节的重要安全手段,本文将介绍如何利用Python实现验证码的自动接收,识别与转发,需要的可以参考下... 目录引言一、准备工作1.1 硬件与软件需求1.2 环境配置二、核心功能实现2.1 短信监听与获取2.

电脑win32spl.dll文件丢失咋办? win32spl.dll丢失无法连接打印机修复技巧

《电脑win32spl.dll文件丢失咋办?win32spl.dll丢失无法连接打印机修复技巧》电脑突然提示win32spl.dll文件丢失,打印机死活连不上,今天就来给大家详细讲解一下这个问题的解... 不知道大家在使用电脑的时候是否遇到过关于win32spl.dll文件丢失的问题,win32spl.dl

pip无法安装osgeo失败的问题解决

《pip无法安装osgeo失败的问题解决》本文主要介绍了pip无法安装osgeo失败的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 进入官方提供的扩展包下载网站寻找版本适配的whl文件注意:要选择cp(python版本)和你py

SpringBoot项目启动报错"找不到或无法加载主类"的解决方法

《SpringBoot项目启动报错找不到或无法加载主类的解决方法》在使用IntelliJIDEA开发基于SpringBoot框架的Java程序时,可能会出现找不到或无法加载主类com.example.... 目录一、问题描述二、排查过程三、解决方案一、问题描述在使用 IntelliJ IDEA 开发基于

SpringCloud之LoadBalancer负载均衡服务调用过程

《SpringCloud之LoadBalancer负载均衡服务调用过程》:本文主要介绍SpringCloud之LoadBalancer负载均衡服务调用过程,具有很好的参考价值,希望对大家有所帮助,... 目录前言一、LoadBalancer是什么?二、使用步骤1、启动consul2、客户端加入依赖3、以服务

Vue 调用摄像头扫描条码功能实现代码

《Vue调用摄像头扫描条码功能实现代码》本文介绍了如何使用Vue.js和jsQR库来实现调用摄像头并扫描条码的功能,通过安装依赖、获取摄像头视频流、解析条码等步骤,实现了从开始扫描到停止扫描的完整流... 目录实现步骤:代码实现1. 安装依赖2. vue 页面代码功能说明注意事项以下是一个基于 Vue.js

OpenManus本地部署实战亲测有效完全免费(最新推荐)

《OpenManus本地部署实战亲测有效完全免费(最新推荐)》文章介绍了如何在本地部署OpenManus大语言模型,包括环境搭建、LLM编程接口配置和测试步骤,本文给大家讲解的非常详细,感兴趣的朋友一... 目录1.概况2.环境搭建2.1安装miniconda或者anaconda2.2 LLM编程接口配置2