Android WebView 调用系统拍照和相册

由于本应用版本较低 未写Android7.0以上权限适配和文件读取适配;

mWebView.setWebViewClient(new MyWebViewClient());

mWebView.setWebChromeClient(new MyWebChromeClient());

WebViewUtils..WebViewSetting(mWebView);



新建WebViewUtils类:

public static void WebViewSetting(WebView webView) {

webView.canGoForward();

    webView.canGoBack();

/*    //支持javascript

webView.getSettings().setJavaScriptEnabled(true);

webView.getSettings().setDomStorageEnabled(true);

    // 设置可以支持缩放webView.getSettings().setSupportZoom(true);

    // 设置出现缩放工具webView.getSettings().setBuiltInZoomControls(true);

    //扩大比例的缩放webView.getSettings().setUseWideViewPort(true);

    //自适应屏幕*/

    WebSettings webSetting = webView.getSettings();

    webSetting.setAllowFileAccess(true);

    webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

    webSetting.setSupportZoom(false);

    webSetting.setBuiltInZoomControls(false);

    webSetting.setUseWideViewPort(true);

    webSetting.setSupportMultipleWindows(false);//这里一定得是false,不然打开的网页中,不能在点击打开了

    // webSetting.setLoadWithOverviewMode(true);

    webSetting.setAppCacheEnabled(true);

    // webSetting.setDatabaseEnabled(true);

    webSetting.setDomStorageEnabled(true);

    webSetting.setJavaScriptEnabled(true);

    webSetting.setGeolocationEnabled(true);

    webSetting.setAppCacheMaxSize(Long.MAX_VALUE);

    // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);

    webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);

    // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);

// webSetting.setPreFectch(true);

// this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extensio

//  webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

    webSetting.setLoadWithOverviewMode(true);

    String ua = webView.getSettings().getUserAgentString();

    webView.getSettings().setUserAgentString(ua.replace("Android", "HFWSH_USER_Android"));

    if (webView.getX5WebViewExtension() !=null) {

//开启X5全屏播放模式

        Bundle data =new Bundle();

        data.putBoolean("standardFullScreen", false);// true表示标准全屏,false表示X5全屏;不设置默认false,

        data.putBoolean("supportLiteWnd", true);// false:关闭小窗;true:开启小窗;不设置默认true,

        data.putInt("DefaultVideoScreen", 2);// 1:以页面内开始播放,2:以全屏开始播放;不设置默认:1

        webView.getX5WebViewExtension().invokeMiscMethod("setVideoParams",

                data);

    }

}

在Activity中自定义WebViewClient

private class MyWebViewClient extends WebViewClient {

final Dialogdialog = DialogUtils.createLoadingDialog(context, "加载中...");

        public MyWebViewClient() {

super();

        }

@Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

if (URLUtil.isNetworkUrl(url)) {

final ConnectionQuality connectionQuality = ConnectionClassManager.getInstance().getCurrentBandwidthQuality();

                String name = connectionQuality.name();

                if (name.equals("POOR")) {

Toast.makeText(context, "当前网络差", Toast.LENGTH_SHORT).show();

                }

view.loadUrl(url);

            }else {

Toast.makeText(context, "链接无效", Toast.LENGTH_SHORT).show();

//                    context.finish();

            }

return true;

        }

@Override

        public void onPageStarted(WebView view, String url, Bitmap favicon) {

super.onPageStarted(view, url, favicon);

            if (dialog !=null) {

dialog.show();

            }

}

@Override

        public void onPageFinished(WebView view, String url) {

super.onPageFinished(view, url);

            DialogUtils.closeDialog(dialog);

            DeviceBandwidthSampler.getInstance().stopSampling();

        }

}


在Activity中自定义WebChromeClient

private class MyWebChromeClient extends WebChromeClient {

// For Android 3.0+

    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {

Log.d(TAG, "openFileChooser");

        if (mUploadMessage !=null)return;

        mUploadMessage = uploadMsg;

        selectImage();

    }

// For Android < 3.0

    public void openFileChooser(ValueCallback uploadMsg) {

openFileChooser(uploadMsg, "");

    }

// For Android  > 4.1.1

    public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {

openFileChooser(uploadMsg, acceptType);

    }

// For Android 5.0

    @Override

    public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {

if (mUploadMessagesAboveL !=null) {

mUploadMessagesAboveL.onReceiveValue(null);

        }else {

mUploadMessagesAboveL = filePathCallback;

            selectImage();

        }

return true;

    }

}


在Activity中调用

常量声明:

private static final StringTAG ="MainActivity";

private static final int REQUEST_CAMERA =1;

private static final int REQUEST_CHOOSE =2;

ValueCallbackmUploadMessage;

ValueCallbackmUploadMessagesAboveL;

private UricameraUri;


/**

* 打开照相机

*/

private void openCarcme() {

Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    String imagePaths = Environment.getExternalStorageDirectory().getPath() +"/yicaitong/Images/" + (System.currentTimeMillis() +".jpg");

    // 必须确保文件夹路径存在,否则拍照后无法完成回调

    File vFile =new File(imagePaths);

    if (!vFile.exists()) {

File vDirPath = vFile.getParentFile();

        vDirPath.mkdirs();

    }else {

if (vFile.exists()) {

vFile.delete();

        }

}

cameraUri = Uri.fromFile(vFile);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);

    startActivityForResult(intent, REQUEST_CAMERA);

}


/**

* 本地相册选择图片

*/

private void chosePicture() {

Intent innerIntent =new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    innerIntent.setType("image/*");

    Intent wrapperIntent = Intent.createChooser(innerIntent, null);

    startActivityForResult(wrapperIntent, REQUEST_CHOOSE);

}

/**

* 选择照片后结束

*

* @param data

*/

private UriafterChosePic(Intent data) {

if (data !=null) {

final String path = data.getData().getPath();

        if (path !=null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {

return data.getData();

        }else {

Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();

        }

}

return null;

}



private void selectImage() {

if (!FileUtils.checkSDcard(this)) {

return;

    }

String[] selectPicTypeStr = {"拍照", "图库"};

    new AlertDialog.Builder(this)

.setOnCancelListener(new ReOnCancelListener())

.setItems(selectPicTypeStr,

                    new DialogInterface.OnClickListener() {

@Override

                        public void onClick(DialogInterface dialog, int which) {

switch (which) {

// 相机拍摄

  case 0:

openCarcme();

break;

                                // 手机相册

    case 1:

chosePicture();

break;

                            }

}

}).show();

}



/**

* 返回文件选择

*/

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

if (mUploadMessagesAboveL !=null) {

onActivityResultAboveL(requestCode, resultCode, intent);

    }

if (mUploadMessage ==null)return;

    Uri uri =null;

    if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {

uri =cameraUri;

        Log.e("onActivityResult: ", uri.toString());

    }

if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {

uri = afterChosePic(intent);

    }

mUploadMessage.onReceiveValue(uri);

    mUploadMessage =null;

    super.onActivityResult(requestCode, resultCode, intent);

}

/**

* 5.0以后机型 返回文件选择

*

* @param requestCode

* @param resultCode

* @param data

*/

private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {

Uri[] results =null;

    if (requestCode ==REQUEST_CAMERA && resultCode ==RESULT_OK) {

results =new Uri[]{cameraUri};

    }

if (requestCode ==REQUEST_CHOOSE && resultCode ==RESULT_OK) {

if (data !=null) {

String dataString = data.getDataString();

            if (dataString !=null)

results =new Uri[]{Uri.parse(dataString)};

        }

}

mUploadMessagesAboveL.onReceiveValue(results);

    mUploadMessagesAboveL =null;

return;

}


/**

* dialog监听类

*/

private class ReOnCancelListenerimplements DialogInterface.OnCancelListener {

@Override

    public void onCancel(DialogInterface dialogInterface) {

if (mUploadMessage !=null) {

mUploadMessage.onReceiveValue(null);

            mUploadMessage =null;

        }

if (mUploadMessagesAboveL !=null) {

mUploadMessagesAboveL.onReceiveValue(null);

            mUploadMessagesAboveL =null;

        }

}

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容