[英]How to use Cache offline, else use network
我正在嘗試創建一個顯示WebView的應用程序。 我希望它在沒有網絡時顯示緩存版本。 否則,如果有可用的網絡,它應該從URL加載WebView。
到目前為止一切都那么好,除非它一直使用緩存版本,即使有網絡可用。 所以我想問一下下面的代碼是否有問題。 似乎我錯過了一些東西。
我已嘗試使用下面的代碼,沒有它。 我發現了以下內容:無論我嘗試什么,似乎該應用程序始終使用“緩存”版本。 此時我甚至不確定它是否真正使用了緩存,因為當我清除App Data(而不是緩存)時,我只能再次從URL加載網站。
Android版本6.0.1 API級別23
mWebView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
mWebView.getSettings().setAllowFileAccess( true );
mWebView.getSettings().setAppCacheEnabled( true );
mWebView.getSettings().setJavaScriptEnabled( true );
mWebView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
if ( !isNetworkAvailable() ) { // loading offline
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
mWebView.loadUrl("https://path.to.my/website/index.html");
預期結果:當手機有網絡時,我希望它從URL獲取網站。
實際結果:安裝完成后,網站已從網址中獲取。 然后,它將只使用緩存版本。 (或者可能是存儲在App Data中的版本。不確定它是如何工作的。)
更新:
我得到了它的工作,它現在看起來像這樣:(不確定這是否是“最佳實踐”方式,但)
WebSettings webSettings = mWebView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setAllowFileAccess( true );
webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
//webSettings.setJavaScriptEnabled( true );
if ( !isNetworkAvailable() ) { // loading offline
webSettings.setCacheMode( WebSettings.LOAD_CACHE_ONLY );
Toast.makeText(mContext, "DEBUG: No net",Toast.LENGTH_SHORT).show();
}
mWebView.loadUrl("https://path.to.my/website/index.html");
if (!isNetworkAvailable()) { // loading offline
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
} else {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.