1. 清空cache
public void clearAPPCache(Context myAppctx) {
if (myAppctx != null) {File cachDir = myAppctx.getCacheDir();
Log.v("Trim", "dir " + cachDir.getPath());
deleteCache(cachDir);
}
}
private void deleteCache(File cachDir) {
if (cachDir != null && cachDir.isDirectory()) {
for (File child : cachDir.listFiles()) {
if (child.isDirectory()) {
deleteCache(child);
} else {
Log.d("================", "delete : " + child.getName());
child.delete();
}
}
}
}
2. 清空过期的cache(转载)
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("ATTENTION!",
String.format("Failed to clean the cache, error %s",
e.getMessage()));
}
}
return deletedFiles;
}