android - 从缓存中加载 webview

标签 android caching webview

我需要在 Internet 访问可用时从 Internet 加载 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");

}

最佳答案

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

要对此进行测试,请使 isNetworkAvailable() 暂时始终返回 false,并在首次加载网页一次后将您的设备置于飞行模式。

关于android - 从缓存中加载 webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17259537/

相关文章:

ruby-on-rails - Rails 3 和 Memcached - 智能缓存,永不过期

.net - 用于从 Appfabric 缓存中删除项目的 Powershell 命令

Javascript 与 Android 的 Webview 交互

android - 我在 webview 中遇到 CertPathValidatorException 问题

java - SQLite 约束异常 : error code 19: constraint failed

android - 防止 Android 终止暂停的音频服务

java - 在数组列表Java中拆分字符串

Android: "BadTokenException: Unable to add window; is your activity running?"在 PreferenceActivity 中显示对话框

ios - AFNetworking 图像缓存在内存警告中未清空

javascript - Android Webview,formhash 在某些 Android 设备上不工作