2012-10-26 61 views
0

在我的ContentView中,我有一些離線內容和一個WebView。當設備在線時,WebView將顯示來自網絡的內容。但是,當設備脫機時,會顯示白頁。我怎樣才能擺脫這個空白頁?我不想在離線模式下顯示任何WebView內容。Android 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); 
    } 
+0

參考這裏http://stackoverflow.com/a/14671256/3981656 –

回答

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(); 

我有同樣的問題。所以我顯示錯誤而不是空白頁面。之後我決定回到我開始網絡的活動。所以我用完(); 。這有助於完成錯誤並返回。

我使用的源代碼是。

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年後。

相關問題