Android WebView在离线模式下显示空白页面

时间:2012-10-26 10:25:54

标签: android webview offline

在我的ContentView中,我有一些离线内容和一个WebView。设备在线时,WebView会显示来自Web的内容。但是当设备离线时,会显示白页。我怎样才能摆脱这个空白页面?我不想在离线模式下显示任何WebView内容。

我的代码是:

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = cm
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo datac = cm
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if ((wifi != null & datac != null)
            && (wifi.isConnected() | datac.isConnected())) {
    android.webkit.WebView wv = 
    (android.webkit.WebView)this.findViewById(R.id.myWebView);
    wv.clearCache(true);
    wv.loadUrl("MyURL");
    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    wv.getSettings().setJavaScriptEnabled(true);
    }

1 个答案:

答案 0 :(得分:0)

如果我理解它是正确的,你希望它显示一些错误而不是空白页面。然后您可以使用以下代码:

mainWebView.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            String summary = "<html><h1>Could not connect to the server</h1><h2>May be you are not connected to Internet or</h2><h3>our server is down.</h3><body>Please exit the program and try again later.</body></html>";
            mainWebView.loadData(summary, "text/html", null);               

        }
    });

或者如果您想在设备离线时返回相同的活动而不是显示空白页面,那么只需使用此代码:

                    mainWebView.onResume();
                    finish();

我遇到了同样的问题。所以我显示错误而不是空白页面。然后我决定回到我开始上网的活动。所以我用了finish(); 。这有助于完成错误并返回。

我使用的源代码是。

mainWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                String summary = "<html><h1>Could not connect to the server</h1><h2>May be you are not connected to Internet or</h2><h3>our server is down.</h3><body>Please exit the program and try again later.</body></html>";
                mainWebView.loadData(summary, "text/html", null);

                Toast.makeText(activity, "Error. Cannot to the server. May be you are not connected to Internet or our server is down or " + description, Toast.LENGTH_LONG)
                        .show();
                mainWebView.onResume();
                    finish();



            }
        });

        mainWebView.loadUrl(getIntent().getStringExtra("url"));

P.S很抱歉回复迟到。我相信1年后。