为了给用户提供一种清除缓存的快速方法,我正在使用以下功能(基于this和this)附加到“清除缓存”按钮上:
static void clearAppCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) {
// TODO: handle exception
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (String aChildren : children) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
return dir.delete();
} else if (dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
我还使用相同的缓存路径设置了WebView,如下所示:
WebSettings webSettings = mWebView.getSettings();
webSettings.setAppCacheEnabled(true);
String cachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webSettings.setAppCachePath(cachePath);
我的理论是,调用clearAppCache()
还会清除WebView的缓存,因为它所做的只是清除与我为WebView设置的相同的缓存文件夹。
但是由于我的WebView现在正在加载使用服务工作者的页面,所以我发现这似乎并没有清除服务工作者缓存。我收到一个用户的报告,为了真正清除服务工作者的东西,他们必须手动清除以下文件夹的内容(在其root用户的设备上):
/data/data/com.example.myapp/app_webview/Cache/
根据这篇文章,我尝试将以下行添加到我的clearAppCache()
函数中:
WebStorage.getInstance().deleteAllData();
但这似乎并没有清除服务工作者缓存的效果。
有任何想法吗?是的,我知道可以使用javascript清除服务工作者缓存(请参阅上面的链接),但是我想要一种直接从Android执行此操作的方法。
我现在找到了一种删除服务工作者缓存的方法。我的数据目录位于:
/data/user/0/com.app.package
然后是:
/cache
/http
/org.chromium.android_webview
/WebView
/code_cache
/files
/shared_prefs
/app_webview
/webview_data.lock
/Web Data
/Web Data-journal
/metrics_guid
/Cookies
/Cookies-journal
/GPUCache
/Service Worker
/QuotaManager
/QuotaManager-journal
/databases
/app_textures
/app_download_internal
/databases
/shaders
请注意,其中存在Service Worker
子目录app_webview
,这是一个赠品。
因此,要清除服务工作者缓存,似乎只需要删除该子目录:
File dataDir = context.getDataDir(); // or see https://stackoverflow.com/a/19630415/4070848 for older Android versions
File serviceWorkerDir = new File(dataDir.getPath() + "/app_webview/Service Worker/");
deleteDir(serviceWorkerDir); // function defined in original post
或者,更残酷的是,您似乎可以删除整个app_webview
子文件夹及其中的所有内容:
File dataDir = context.getDataDir(); // or see https://stackoverflow.com/a/19630415/4070848 for older Android versions
File appWebViewDir = new File(dataDir.getPath() + "/app_webview/");
deleteDir(appWebViewDir); // function defined in original post
仍然令我困惑的是,尽管将WebView的缓存路径设置为webSettings.setAppCachePath(cachePath)
在缓存目录中(请参阅我的原始文章),但WebView还是选择app_webview
用于服务人员缓存。也许它将缓存目录用于传统的http缓存,并选择其自己的位置(app_webview
)用于服务工作者的缓存?但这似乎仍然不正确。此外,如前所述,一个用户报告了中存在一个Cache
子目录app_webview
,并且他们位于不支持服务工作者的KitKat(Android 4.4)上……不确定为什么使用该app_webview/Cache
目录而不是(或在其中)除了)cache
。我一点都没有app_webview/Cache
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句