简体   繁体   中英

How to detect cache is existed for the webview in android?

In my android application need to detect cache is existed or not. Currently i am loading webpages if internet is available. If internet is not available loading pages from caches by using the following code.

if (networkInfo.isConnected()) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default
        } else {
            // loading offline
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

In the above code i need to add one more condition for internet is not available and cache also not available then i need to show message to the user. So planning to identify any cache is available for webview. But unable to find a way to determine cache is available or not.

Have the following ideas but no idea how to achieve my goal. 1.Find out a method of weview or webviewsettings to return isCacheAvailable like method. Did not find it. 2.Find out the exact path for webview cache file. So that i can check the file size to determine the cache available or not. But did not find the way to get exact path for webview cache directory.

Please help me to find out a way to identify webview cache is existed or not.

The path for webview cache is getApplicationContext().getCacheDir()

so the method can be

private boolean isCacheAvailable(){
    File dir  = getApplicationContext().getCacheDir();
    if (dir.exists())
        return dir.listFiles().length > 0;
    else
        return false;
};

webview 缓存保存到 /data/data/[your_package_name]/cache/org.chromium.android_webview 文件夹中。

This works for me

Yes 5 is a magic number, real files count is about 50

After clean cache files count is 2-3

class WebClient : WebViewClient() {

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        return false
    }

    override fun onReceivedError(view: WebView, errorCode: Int, description: String?, failingUrl: String) {
        view.apply {
            File(context.cacheDir, "org.chromium.android_webview").let {
                if (!it.exists() || it.listFiles()?.size ?: 0 < 5) {
                    // not cached
                }
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    override fun onReceivedError(view: WebView, req: WebResourceRequest, rerr: WebResourceError) {
        onReceivedError(view, rerr.errorCode, rerr.description?.toString(), req.url.toString())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM