从缓存加载webview

时间:2013-06-23 09:50:27

标签: android caching webview

我需要在互联网访问可用时从互联网加载mWebview 。当它不可用时,它需要从缓存中加载。我有一些东西,但根本没有加载网站

请帮帮我?

许可我已添加:
  - android.permission.INTERNET
  - android.permission.WRITE_EXTERNAL_STORAGE
  - android.permission.ACCESS_NETWORK_STATE

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


@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Layout Webview
    mWebview  = new WebView(this);
    // Broadcast
    Toast.makeText(this, "Laden van roosterwijzigingen.",
    Toast.LENGTH_SHORT).show();
    // Enable JavaScript
    mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
    mWebview.setHorizontalScrollBarEnabled(false);
    mWebview.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
    mWebview.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
    mWebview.getSettings().setAllowFileAccess( true );
    mWebview.getSettings().setAppCacheEnabled( true );
    mWebview.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
    final Activity activity = this;
    // Make WebClient
    mWebview.setWebViewClient(new WebViewClient() { 
    // Trace Errors
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
    }
}); 
    if ( !isNetworkAvailable() ) { // loading offline
        mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
    }

    mWebview.loadUrl("http://divers.ommelandercollege.nl/webportalen/dagrooster.php");

}

2 个答案:

答案 0 :(得分:0)

我检查了你的代码,缓存工作正常(用http://yahoo.com测试)。您的问题必须采用isNetworkAvailable()方法,因此必须采用。{ setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK)未被调用。

要对此进行测试,请isNetworkAvailable()暂时返回false,并在首次加载wepbage后将设备置于飞行模式。

答案 1 :(得分:-1)

if ( !isNetworkAvailable() ) { // loading offline
    mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
style="color:red">}// move this bracket

mWebview.loadUrl("http://divers.ommelandercollege.nl/webportalen/dagrooster.php");
// to here  } 
}