Android WebView,从缓存加载并尝试刷新

时间:2018-04-04 10:46:17

标签: java android android-webview swiperefreshlayout

我正在尝试创建一个加载网页并将其存储在缓存中的小应用程序。刷卡刷新时必须尝试更新,但如果没有互联网访问权限,则应保留当前版本。

目前,我已经通过刷卡强制刷新"和#34;从缓存中加载"工作,但似乎无法弄清楚如何尽可能地刷新"。

swipeRefreshLayout = findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(
        new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                myWebView.clearCache(true);
                myWebView.reload();
            }
        }
);

WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

myWebView.loadUrl(config.getString("website_root"));
myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        swipeRefreshLayout.setRefreshing(false);
    }
});

1 个答案:

答案 0 :(得分:0)

基于WebSettings.LOAD_CACHE_ELSE_NETWORK的{​​{3}}:

  

使用缓存资源,即使它们有   过期。否则从网络加载资源

因此,您始终从缓存加载视图。

您可以使用以下方法: 1.检查连接性:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
}
  1. 之前而不是设置:

    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
    
    webSettings.setCacheMode(isNetworkConnected()?WebSettings.LOAD_NO_CACHE: WebSettings.LOAD_CACHE_ONLY);
    
  2. 在滑动刷新时,您可以这样做:

    swipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    if(isNetworkConnected()){
                        ...
                        myWebView.reload();
                    } else {
                          //Do something for non-connectivity
                    }
            }
        });