美文网首页
Android webView 打开相册

Android webView 打开相册

作者: 我叫杨毅 | 来源:发表于2023-09-07 14:28 被阅读0次
     private static final int CHOOSE_REQUEST_CODE = 0x9001;
        private ValueCallback<Uri> uploadFile;//定义接受返回值
        private ValueCallback<Uri[]> uploadFiles;
    
    
    public void initView() {
            mPresenter = new WebPresenter();
            mPresenter.attachView(this);
            webView = findViewById(R.id.webView);
            ivError = findViewById(R.id.ivError);
            webView.setWebContentsDebuggingEnabled(true);
            //订阅这个EventBus
            EventBus.getDefault().register(this);
    
            /**
             * js像Android发送消息
             * */
            webView.addJavascriptInterface(new WebAppInterface(this), "Android");
    
            //判断通知权限是否开启
            if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
                //跳转开启通知页面
                jumpNotificationSetting();
            }
            //相册如果未授权
            if (ContextCompat.checkSelfPermission(WebActivity.this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //发起授权询问
                ActivityCompat.requestPermissions(WebActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, 1);
            }
    
    //                Intent intent = new Intent(Intent.ACTION_PICK,
    //                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    //        startActivityForResult(intent, 11);
    
    
            // webView加载web文件
    //        webView.loadUrl(SharedPreferencesUtil.getString("url"));
            webView.setWebContentsDebuggingEnabled(true);
            WebSettings settings = webView.getSettings();
            // 不使用缓存:
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            // 启用支持javaScript
            settings.setJavaScriptEnabled(true);
            // 自動播放
            settings.setMediaPlaybackRequiresUserGesture(false);
            // 开启支持H5
            settings.setDomStorageEnabled(true);  // 开启支持H5
    
    
            //设置webview支持javascript
            settings.setJavaScriptEnabled(true);
            //增加 设置脚本是否允许自动打开弹窗
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            //支持自动加载图片
            settings.setLoadsImagesAutomatically(true);
            //设置webview推荐使用的窗口,使html界面自适应屏幕
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);
            //设置webview保存表单数据
            settings.setSaveFormData(true);
            //设置webview保存密码
            settings.setSavePassword(true);
    //        int mDensity = getResources().getDisplayMetrics().densityDpi;
    //        if (mDensity == 120) {
    //            settings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
    //        } else if (mDensity == 160) {
    //            settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    //        } else if (mDensity == 240) {
    //            settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    //        }
            //支持缩放
            settings.setSupportZoom(true);
            settings.setSupportMultipleWindows(true);
            //设置APP可以缓存
            settings.setAppCacheEnabled(true);
            settings.setDatabaseEnabled(true);
            //返回上个界面不刷新  允许本地缓存
            settings.setDomStorageEnabled(true);
            //增加 设置缓存LOAD_DEFAULT   LOAD_CACHE_ONLY,LOAD_NO_CACHE
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
            // 设置可以访问文件
            settings.setAllowFileAccess(true);
            //不支持放大缩小
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            //不支持放大缩小
            settings.setDisplayZoomControls(false);
    
            //增加 设置编码格式
            settings.setDefaultTextEncodingName("utf-8");
    
            webView.setLongClickable(true);
            webView.setScrollbarFadingEnabled(true);
            webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            webView.setDrawingCacheEnabled(true);
    
    
            // 覆盖webview默认通过第三方或者系统浏览器打开网页的行为,使得网页在webview中打开
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //返回值为true,在webview中打开,返回值为false在第三方或者系统浏览器打开网页
                    view.loadUrl(url);
                    return false;
                }
    
                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) {
                    // 重写此方法可以让webview处理https请求
                    handler.proceed();
                }
            });
            // 显示进度,出现一个进度窗口
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    //newProgress 1-100之间的整数
                    try {
                        if (newProgress == 100) {
                            // 网页加载完毕,关闭progressDialog
                            CommonMvpActivity.dismiss();
                        } else {
                            //网页正在加载,打开progressDialog
                        }
                    } catch (Exception e) {
                        Log.e("WebUtils-----------", "");
                    }
                }
    
    
                /**
                 * Android 5.0
                 * @param webView
                 * @param filePathCallback
                 * @param fileChooserParams
                 * @return
                 */
    // For Android  >= 5.0
                @Override
                public boolean onShowFileChooser(WebView webView,
                                                 ValueCallback<Uri[]> filePathCallback,
                                                 WebChromeClient.FileChooserParams fileChooserParams) {
                    uploadFiles = filePathCallback;
                    openFileChooseProcess();
                    return true;
                }
    
                private void openFileChooseProcess() {
                    // 文件夹
    //                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    //                i.addCategory(Intent.CATEGORY_OPENABLE);
    //                i.setType("image/*");
    //                startActivityForResult(Intent.createChooser(i, "Choose"), CHOOSE_REQUEST_CODE);
    
                    // 相册
                    Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, CHOOSE_REQUEST_CODE);
    
    //                // 相机
    //                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    //                startActivityForResult(intent, CHOOSE_REQUEST_CODE);
    
                }
    
    
            });
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
            });
    
    
        }
    
    
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //        LogCat.d("requestCode===",requestCode+"====");
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == Activity.RESULT_OK) {
                switch (requestCode) {
                    case CHOOSE_REQUEST_CODE:
    
                        if (null != uploadFile) {
                            Uri result = data == null || resultCode != Activity.RESULT_OK ? null
                                    : data.getData();
                            uploadFile.onReceiveValue(result);
                            uploadFile = null;
                        }
                        if (null != uploadFiles) {
                            Uri result = data == null || resultCode != Activity.RESULT_OK ? null
                                    : data.getData();
                            uploadFiles.onReceiveValue(new Uri[]{result});
                            uploadFiles = null;
                        }
                        break;
                    default:
                        break;
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(null);
                    uploadFile = null;
                }
                if (null != uploadFiles) {
                    uploadFiles.onReceiveValue(null);
                    uploadFiles = null;
                }
            }
        }
    
    

    相关文章

      网友评论

          本文标题:Android webView 打开相册

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