如何检查URL是否在webview中加载

时间:2011-12-02 06:46:58

标签: android url webview connectivity

我使用下面的代码

在android webview中加载url
webviewShowPost.loadUrl(URL);

我想检查是否没有可用的数据连接,然后是webview而不是显示空白视图,我可以显示没有连接的Toast。

由于

5 个答案:

答案 0 :(得分:8)

请试试这个

webView.setWebViewClient(new WebViewClient() { 
        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
        }


    });

答案 1 :(得分:2)

public static boolean isOnline(Context context) {

        try {
            ConnectivityManager cm = (ConnectivityManager) context

            .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {

                URL url = new URL("http://www.google.com.pk/");
                                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setConnectTimeout(1000); // mTimeout is in seconds

                urlc.connect();

                if (urlc.getResponseCode() == 200) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

答案 2 :(得分:2)

您可以在上面的webview方法中获取进度百分比值

 mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress)  
        {
         //Make the bar disappear after URL is loaded, and changes string to Loading...
     //Make the bar disappear after URL is loaded
         System.out.println("Value of progress"+progress);
            pbweb.setProgress(progress);

            if(progress == 100)


            pbweb.setVisibility(View.GONE);
          }
        });

正在进行中的代码是progerss的值

答案 3 :(得分:0)

您想在加载页面之前检查是否存在网络连接,这意味着您要执行此操作:https://stackoverflow.com/a/2001824/960048

答案 4 :(得分:0)

您始终可以使用WebViewClient来实现此目的。

    web.setWebViewClient(new WebViewClient(){

         public void onReceivedError(WebView view, int errorCode, String description,String failingUrl) {
             Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
         }
    });