我有一个 WebView 控件,我想每次显示当前站点,但我认为 WebView 只显示站点的缓存版本。我尝试了这里找到的所有东西,但似乎没有任何效果。我还尝试从 context.getCacheDir() 中删除所有文件,但没有成功。我能做些什么?
这是我来自 onCreate 方法的代码:
clearCache(this, 0);
setContentView(R.layout.webview);
deleteDatabase("webview.db");
deleteDatabase("webviewCache.db");
mWebView = (WebView)findViewById(R.id.webview);
mWebView.setWebViewClient(new CenterWebViewClient(this));
mWebView.setWebChromeClient(new CenterWebChromeClient(this));
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setAppCacheMaxSize(1);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String url = "https://www.exacmple.com";
if (url != null) {
Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
noCacheHeaders.put("Pragma", "no-cache");
noCacheHeaders.put("Cache-Control", "no-cache");
mWebView.loadUrl(url, noCacheHeaders);
}
清除缓存功能:
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e("WebView", String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
public static void clearCache(final Context context, final int numDays) {
Log.i("WebView", String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i("WebView", String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}