3

在我的 android 应用程序中需要检测缓存是否存在。目前,如果互联网可用,我正在加载网页。如果互联网不可用,则使用以下代码从缓存中加载页面。

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

在上面的代码中,我需要添加一个互联网不可用且缓存也不可用的条件,然后我需要向用户显示消息。因此,计划识别任何缓存可用于 webview。但是无法找到确定缓存是否可用的方法。

有以下想法,但不知道如何实现我的目标。1.找一个weview或者webviewsettings的方法返回isCacheAvailable之类的方法。没找到。2.找出webview缓存文件的确切路径。这样我就可以检查文件大小以确定缓存是否可用。但没有找到获取 webview 缓存目录的确切路径的方法。

请帮我找出一种方法来识别 webview 缓存是否存在。

4

3 回答 3

2

webview缓存的路径是getApplicationContext().getCacheDir()

所以方法可以是

private boolean isCacheAvailable(){
    File dir  = getApplicationContext().getCacheDir();
    if (dir.exists())
        return dir.listFiles().length > 0;
    else
        return false;
};
于 2016-12-27T08:39:05.027 回答
1

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

于 2017-08-09T11:04:20.910 回答
0

这对我有用

是的 5 是一个幻数,实际文件数约为 50

清理缓存文件后计数为 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())
    }
}
于 2019-07-31T17:08:16.047 回答