Clear Cache WebView

1 Introduction

Used WebView students are clear, WebView default is automatically cached web resources. While the front pages H5 has its own set of caching mechanism (the students do not understand, you can read this article  taught you how to build Android WebView cache mechanism & Resources preloaded program ), but in some scenarios, still need to take the initiative to go native make clear the cache operation, that is clear WebView cache. Most articles will say, use the following methods can be cleared.

new WebView(context).clearCache(true);

But in fact this is the way cleared, cleared only part of the cache only. Like Cookie, this way is not clear.

2. Solution

Through their own exploration, sorting out an effective way to clear, specific code as follows:

/**
 * 清除缓存
 *
 * @param context 上下文
 */
public static void clearCache(Context context) {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 清除cookie
            CookieManager.getInstance().removeAllCookies(null);
        } else {
            CookieSyncManager.createInstance(context);
            CookieManager.getInstance().removeAllCookie();
            CookieSyncManager.getInstance().sync();
        }

        new WebView(context).clearCache(true);

        File cacheFile = new File(context.getCacheDir().getParent() + "/app_webview");
        clearCacheFolder(cacheFile, System.currentTimeMillis());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static int clearCacheFolder(File dir, long time) {
    int deletedFiles = 0;
    if (dir != null && dir.isDirectory()) {
        try {
            for (File child : dir.listFiles()) {
                if (child.isDirectory()) {
                    deletedFiles += clearCacheFolder(child, time);
                }
                if (child.lastModified() < time) {
                    if (child.delete()) {
                        deletedFiles++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return deletedFiles;
}

3. Verify

  • After clearCache call the above method, it can re-open the Web page speed, compare page load
  • Android Studio DeviceFileExplorer using the tool, to the next "/ dada / data / APP package name" directory, file contents before and after the change, as shown in FIG.
Before clearing cache
After clearing the cache

 

You can view the complete demo  AndroidWebView .

 

Published 43 original articles · won praise 34 · views 90000 +

Guess you like

Origin blog.csdn.net/Fantasy_Lin_/article/details/104068174