码上啥都有 - webview无响应的问题
type: channel
link: https://litecoder.top/index.php/tag/webview%E6%97%A0%E5%93%8D%E5%BA%94%E7%9A%84%E9%97%AE%E9%A2%98/
items: 关于webview上传图片的坑

关于webview上传图片的坑
type: item
date: 2016-09-01T11:36:21+08:00
description: 项目中遇到了需要在webview上传图片的需求，搜索了一把，找到几个可行的方法，同时也踩了个webview的坑，总结一下我找到的是这样的方法***首先 重写WebChromeClient 添加openFileChooser 方法 // For Android 3.0+public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {//最终调用的都是这个if (mUploadMessage != null) return;//坑就在这里 看后边注释mUploadMessage = uploadMsg;selectImage();}// For Android < 3.0public void openFileChooser(ValueCallback<Uri> uploadMsg) {openFileChooser(uploadMsg, "");}// For Android > 4.1.1public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {openFileChooser(uploadMsg, acceptType);}*** 然后自己实现selectImage()方法```private void selectImage() {//模仿IOS的弹出框List<map <String, String>> list = new ArrayList<>();HashMap ch1 = new HashMap<>();HashMap ch2 = new HashMap<>();HashMap ch3 = new HashMap<>();ch1.put("key", "从相册选择");ch2.put("key", "拍照上传");ch3.put("key", "取消"); list.add(ch1);list.add(ch2);list.add(ch3);ListAdapter ad = new SimpleAdapter(this, list, R.layout.my_simple_list_item_1, new String[]{"key"}, new int[]{android.R.id.text1});chosePicDialog = new AlertDialog.Builder(this).setAdapter(ad, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {switch (i) {case 0:getImageFromAlbum();break;case 1:getImageFromCamera();break;case 2:mUploadMessage.onReceiveValue(null);//这里是坑，如果取消了 不调用这句mUploadMessage.onReceiveValue()的话 整个webview就都没有响应了mUploadMessage = null;//还有这里 上边已标出break;}}}).setCancelable(false).create();chosePicDialog.getWindow().setGravity(Gravity.BOTTOM);chosePicDialog.show();} ```然后分别实现 从图库选择和拍照上传的方法```/*** 调用相册/protected void getImageFromAlbum() {Intent intent = new Intent(Intent.ACTION_PICK);intent.setType("image/");//相片类型startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);} /*** 调用相机*/protected void getImageFromCamera() {//这里采用的是获取拍照原图的方法String state = Environment.getExternalStorageState();if (state.equals(Environment.MEDIA_MOUNTED)) {File f = FileUtil.getNewPicFilePath();Uri u = Uri.fromFile(f);Intent intent = new I…