簡體   English   中英

如何使用Cache離線,否則使用網絡

[英]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");

問題出在LOAD_DEFAULT 官方文件

LOAD_DEFAULT

默認緩存使用模式。 如果導航類型未強加任何特定行為,請在緩存資源可用且未過期時使用緩存資源,否則從網絡加載資源。

當您希望從網絡加載時,它將從緩存加載。

有網絡時試試這個:

mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

當沒有網絡時,使用:

mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);

有關詳細信息,請參閱此答案

   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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM