当我从 setWebChromeClient 使用时,我无法从 onPageStarted webView 使用 - Android

Posted

技术标签:

【中文标题】当我从 setWebChromeClient 使用时,我无法从 onPageStarted webView 使用 - Android【英文标题】:When I use from setWebChromeClient I can't use from onPageStarted webView - Android 【发布时间】:2018-10-05 14:47:23 【问题描述】:

我正在使用下面的代码在webView 中上传文件:

    @SuppressLint("SetjavascriptEnabled")
    private void loadWebView(String url) 
        if (getActivity() != null) 

            if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) 
                ActivityCompat.requestPermissions(getActivity(), new String[]Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, 1);
            

            WebSettings webSettings = webViewRequest.getSettings();

            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setJavaScriptEnabled(true);
            webViewRequest.clearHistory();
            webViewRequest.setHorizontalScrollBarEnabled(false);
            webViewRequest.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

            webSettings.setAllowFileAccess(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setSupportMultipleWindows(true);


            webViewRequest.loadUrl(url);

            if (Build.VERSION.SDK_INT >= 21) 
                webSettings.setMixedContentMode(0);
                webViewRequest.setLayerType(View.LAYER_TYPE_HARDWARE, null);
             else if (Build.VERSION.SDK_INT >= 19) 
                webViewRequest.setLayerType(View.LAYER_TYPE_HARDWARE, null);
             else if (Build.VERSION.SDK_INT < 19) 
                webViewRequest.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            
            webViewRequest.setWebViewClient(new Callback());

            webViewRequest.setWebChromeClient(new WebChromeClient() 

                @Override
                public void onProgressChanged(WebView view, int newProgress) 
                    super.onProgressChanged(view, newProgress);
                    if (newProgress == 100) 
                        if (progressRequestWebView.getVisibility() == View.VISIBLE) 
                            progressRequestWebView.setVisibility(View.GONE);
                        
                    
                

                //For android 3.0+
                public void openFileChooser(ValueCallback<Uri> uploadMsg) 
                    mUM = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("*/*");
                    WebViewRequestFragment.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
                

                // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
                public void openFileChooser(ValueCallback uploadMsg, String acceptType) 
                    mUM = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("*/*");
                    WebViewRequestFragment.this.startActivityForResult(
                            Intent.createChooser(i, "File Browser"),
                            FCR);
                

                //For Android 4.1+
                public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) 
                    mUM = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("*/*");
                    WebViewRequestFragment.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), WebViewRequestFragment.FCR);
                

                //For Android 5.0+
                @Override
                public boolean onShowFileChooser(
                        WebView webView, ValueCallback<Uri[]> filePathCallback,
                        WebChromeClient.FileChooserParams fileChooserParams) 
                    if (mUMA != null) 
                        mUMA.onReceiveValue(null);
                    
                    mUMA = filePathCallback;
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) 
                        File photoFile = null;
                        try 
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCM);
                         catch (IOException ex) 
                            //Log.e(TAG, "Image file creation failed", ex);
                        
                        if (photoFile != null) 
                            mCM = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                         else 
                            takePictureIntent = null;
                        
                    
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    contentSelectionIntent.setType("*/*");
                    Intent[] intentArray;
                    if (takePictureIntent != null) 
                        intentArray = new Intent[]takePictureIntent;
                     else 
                        intentArray = new Intent[0];
                    

                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, FCR);
                    return true;
                

            );
        
    

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) 
        super.onActivityResult(requestCode, resultCode, intent);
        if (Build.VERSION.SDK_INT >= 21) 
            Uri[] results = null;
            //Check if response is positive
            if (resultCode == Activity.RESULT_OK) 
                if (requestCode == FCR) 
                    if (null == mUMA) 
                        return;
                    
                    if (intent == null) 
                        //Capture Photo if no image available
                        if (mCM != null) 
                            results = new Uri[]Uri.parse(mCM);
                        
                     else 
                        String dataString = intent.getDataString();
                        if (dataString != null) 
                            results = new Uri[]Uri.parse(dataString);
                        
                    
                
            
            mUMA.onReceiveValue(results);
            mUMA = null;
         else 
            if (requestCode == FCR) 
                if (null == mUM) return;
                Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            
        
    

    public class Callback extends WebViewClient 
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
            Toast.makeText(getActivity(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        
    

    private File createImageFile() throws IOException 
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    

    @Override
    public void onConfigurationChanged(Configuration newConfig) 
        super.onConfigurationChanged(newConfig);
    

当用户触摸 webView 上的任何链接但不起作用时,我需要使用以下代码:

webViewRequest.setWebViewClient(new WebViewClient() 

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) 
                    super.onPageStarted(view, url, favicon);
                    if (url.contains("GetAttachment")) 
                        cookies = CookieManager.getInstance().getCookie(url);
                        urlDown = url;
                        if (checkPermission()) 
                            startDownload(urlDown, cookies);
                         else 
                            requestPermission();
                        
                    
                
);

【问题讨论】:

Get clicked url in web view in Android的可能重复 @ADM 。不工作。 什么机器人工作?指定有问题。您需要覆盖shouldOverrideUrlLoading() 我测试过,没有得到任何东西。 【参考方案1】:

我现在删除波纹管和好工作:

webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);

【讨论】:

以上是关于当我从 setWebChromeClient 使用时,我无法从 onPageStarted webView 使用 - Android的主要内容,如果未能解决你的问题,请参考以下文章

为啥 webView.setWebChromeClient(new WebChromeClient());导致屏幕变黑?

setWebViewClient 与 setWebChromeClient 有啥区别?

Android WebView的使用

Android 控件WebView显示网页

当我从 TabFragment 使用 LoaderManager 启动片段时,为啥 Tablayout 和 Viewpager 会因 NullpointerException 而崩溃?

当我从样式组件中使用我自己的库时出现无效的钩子调用错误