美文网首页
比较完整的WebView 支持

比较完整的WebView 支持

作者: 黑白岩 | 来源:发表于2018-12-07 14:36 被阅读0次

    比较完整的一个WebView 可以拿过来直接用 写的有一点点乱,大家将就的这使用,
    包含的内容 url拦截, 支持<input type = file>标签 选择手机图片 返回图片 ,js交互 ,还有进度条内容
    其中 持<input type = file>标签 选择手机图片中 主要是 设置 webChromeClient中的 可以看到 onActivityResult 中返回图片 .

    
    public class WebViewActivity extends BaseActivity {
        
        @BindView(R.id.web_view)
        WebView mWebView;
        @BindView(R.id.progress_bar)
        ProgressBar progressBar;
    
        private ValueCallback<Uri> mUploadMessage;
        public ValueCallback<Uri[]> uploadMessage;
        public static final int REQUEST_SELECT_FILE = 100;
        private final static int FILECHOOSER_RESULTCODE = 2;
    
    
        @Override
        protected int getLayoutId() {
            return R.layout.activity_web_view;
        }
    
        @Override
        protected void initParams() {
           
            initWebView();
    
        }
    
        // 对webView 进行初始化设置
        private void initWebView() {
            WebSettings mWebSettings = mWebView.getSettings();
            mWebSettings.setLoadWithOverviewMode(true);
            mWebSettings.setUseWideViewPort(true);
            mWebSettings.setDefaultTextEncodingName("utf-8");
            mWebSettings.setLoadsImagesAutomatically(true);
            mWebSettings.setSupportZoom(true);                //支持放大缩小
            mWebSettings.setBuiltInZoomControls(true);
            mWebSettings.setDisplayZoomControls(false);   //不显示webview缩放按钮       
            mWebSettings.setJavaScriptEnabled(true);   //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
    
            saveData(mWebSettings);
    
            newWin(mWebSettings);
    
            //setWebChromeClient辅助WebView处理JavaScript的对话框,网站图标,网站title,加载进度等
            mWebView.setWebChromeClient(webChromeClient); 
             //setWebClient帮助WebView处理各种通知、请求事件
            mWebView.setWebViewClient(webViewClient);
    
        }
    
        // 
        WebViewClient webViewClient = new WebViewClient() {
    
            /**
             * 多页面在同一个WebView中打开,就是不新建activity或者调用系统浏览器打开
             * 在这里进行 url地址拦截
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
    
        };
    
        WebChromeClient webChromeClient = new WebChromeClient() {
    
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }
    
            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }
    
            //设置 进度条
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                setProgressBar(view, newProgress);
                super.onProgressChanged(view, newProgress);
            }
    
    
             //=========以下都是对html 标签页 中含有标签<input type = file/>  选择图片进行拦截的  选择图片对应的重写onActivityResult==========================================================
            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }
    
            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                uploadMessage = filePathCallback;
                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                   uploadMessage = null;
                    Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }
    
            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }
    
    
            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
    
    
            //=========HTML5定位==========================================================
    
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                                                           final GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);//注意个函数,第二个参数就是是否同意定位权限,第三个是是否希望内核记住
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
    
            //=========多窗口的问题==========================================================
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog,
                                          boolean isUserGesture, Message resultMsg) {
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(view);
                resultMsg.sendToTarget();
                return true;
            }
    
        };
    
    
        /**
         * HTML5数据存储
         */
        private void saveData(WebSettings mWebSettings) {
            //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
            mWebSettings.setDomStorageEnabled(true);
            mWebSettings.setDatabaseEnabled(true);
            mWebSettings.setAppCacheEnabled(true);
            String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
            mWebSettings.setAppCachePath(appCachePath);
        }
    
    
        private void setProgressBar(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                progressBar.setProgress(newProgress);//设置进度值
            }
    
        }
    
    
        /**
         * 多窗口的问题
         */
        private void newWin(WebSettings mWebSettings) {
            //html中的_bank标签就是新建窗口打开,有时会打不开,需要加以下
            //然后 复写 WebChromeClient的onCreateWindow方法
            mWebSettings.setSupportMultipleWindows(false);
            mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        }
    
    
    
        // 返回上一级 而不是退出webView
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        
        @Override
        protected void onDestroy() {
            super.onDestroy();
    
            if (mWebView != null) {
                mWebView.clearHistory();
                ((ViewGroup) mWebView.getParent()).removeView(mWebView);
                mWebView.loadUrl("about:blank");
                mWebView.stopLoading();
                mWebView.setWebChromeClient(null);
                mWebView.setWebViewClient(null);
                mWebView.destroy();
                mWebView = null;
            }
        }
    
    
        // 选择图片 返回图片数据 操作
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (requestCode == REQUEST_SELECT_FILE) {
                    if (uploadMessage == null)
                        return;
                    uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                    uploadMessage = null;
                }
            } else if (requestCode == FILECHOOSER_RESULTCODE) {
                if (null == mUploadMessage)
                    return;
                // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
                // Use RESULT_OK only if you're implementing WebView inside an Activity
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            } else
                Toast.makeText(getBaseContext(), "选择图片失败", Toast.LENGTH_LONG).show();
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:比较完整的WebView 支持

          本文链接:https://www.haomeiwen.com/subject/enythqtx.html