2015-06-21 84 views
0

我實際上是新的編程在Java中,但我一直在我的問題幾個解決方案在這裏,但沒有找到一個適合我的情況,我似乎無法正確地取下代碼。如何webview離線和在線加載網站內容在Android

我想要一個WebView,當手機在線時打開一個在線頁面(例如谷歌),當手機處於離線狀態時打開一個本地html頁面。

雖然我希望手機在聯機時覆蓋本地頁面,以便離線本地頁面始終更新到最後一次手機連接到互聯網。

任何想法如何做到這一點?一些簡單的指向正確的方向可能會有所幫助。

非常感謝

我的源代碼

 WebView engine=(WebView)findViewById(R.id.webView); 
     engine.getSettings().setJavaScriptEnabled(true); 
     engine.getSettings().setBuiltInZoomControls(true); 
     engine.getSettings().setLoadsImagesAutomatically(true); 
       engine.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); 
     engine.setInitialScale(1); 

     engine.setWebChromeClient(new WebChromeClient() { 
       @Override 
       public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,QuotaUpdater quotaUpdater) 
       { 
         quotaUpdater.updateQuota(spaceNeeded * 2); 
       } 
       public void onProgressChanged(WebView view, int progress) 
       { 
        activity.setTitle("Loading..."); 
        activity.setProgress(progress * 100); 



        if(progress == 100) 
        { activity.setTitle(R.string.app_name); 

        } 
       } 
      }); 
     engine.getSettings().setDomStorageEnabled(true); 
     // Set cache size to 8 mb by default. should be more than enough 
     engine.getSettings().setAppCacheMaxSize(1); 
     engine.getSettings().setAllowFileAccess(true); 
     engine.getSettings().setAppCacheEnabled(true); 
     engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); 
     Map<String, String> noCacheHeaders = new HashMap<String, String>(2); 
     noCacheHeaders.put("Pragma", "no-cache"); 
     noCacheHeaders.put("Cache-Control", "no-cache"); 
     // engine.loadUrl("http://www.stackhand.com", noCacheHeaders); 

     cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE); 
     if(cm.getActiveNetworkInfo().isConnected()) 
     { 
     engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); 

     } 
      else{ 
       engine.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); 

      } 



     engine.loadUrl("http://www.stackhand.com", noCacheHeaders); 

使用此功能的在線檢查網絡和離線

private boolean isNetworkAvailable() { 
     ConnectivityManager connectivityManager = (ConnectivityManager)  
     getSystemService(CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
     return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
    } 

回答

1

首先創建HTML自己的網頁,你要離線期間展示。並將其放入資產文件夾中,我們稱之爲mypage.html然後用onReceivedError: 添加以下代碼,

mWebView.setWebViewClient(new WebViewClient() { 
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
    mWebView.loadUrl("file:///android_asset/mypage.html"); 

}