如何在离线时缓存URL并加载?

时间:2017-07-12 09:18:40

标签: android android-webview offline-caching

这是我的代码。由于我是andorid的新手,我不知道该怎么做。这就是我尝试过的。我是否需要一些方法来将缓存保存到存储中?


public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        String url="https://www.facebook.com";

        WebView webView = (WebView) findViewById(R.id.webview_new);
        webView.setWebViewClient(new WebViewClient());

        if(!isNetworkAvailable()){
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webView.loadUrl(url);
    }



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

1 个答案:

答案 0 :(得分:1)

您可以在cache()之前添加此isNetworkAvailable(),以便您可以离线加载网址。

private void cache() {
        webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default
        if (!isNetworkAvailable()) { // loading offline
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
    }