Skip to content

Instantly share code, notes, and snippets.

@saiday
Created August 20, 2019 10:34
Show Gist options
  • Save saiday/66cb59f4caf88a8d7642692756991db6 to your computer and use it in GitHub Desktop.
Save saiday/66cb59f4caf88a8d7642692756991db6 to your computer and use it in GitHub Desktop.
Clear Android web view cache
//helper method for clearCache() , recursive
//returns number of deleted files
fun clearCacheFolder(dir: File?, numDays: Int): Int {
var deletedFiles = 0
if (dir != null && dir!!.isDirectory()) {
try {
for (child in 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() < Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++
}
}
}
} catch (e: Exception) {
Log.e("Clear WebView Cache", String.format("Failed to clean the cache, error %s", e.message))
}
}
return deletedFiles
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
fun clearCache(context: Context, numDays: Int) {
Log.i("Clear WebView Cache", String.format("Starting cache prune, deleting files older than %d days", numDays))
val numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays)
Log.i("Clear WebView Cache", String.format("Cache pruning completed, %d files deleted", numDeletedFiles))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment