public void trimCache() {
try {
File dir = this.getCacheDir();
File appDir = new File(dir.getParent());
if (appDir != null && appDir.isDirectory()) {
new clearcache().execute(appDir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public class clearcache extends AsyncTask<File ,Void, Void>{
@Override
protected Void doInBackground(File... params) {
deleteDir(params[0]);
Log.d("clearcache", params[0].length()+"");
return null;
}
public boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
我使用上面的代码清除我的缓存内存,但这也删除了我的数据库更新。如何在不影响数据库更新的情况下清除缓存(图像缓存)?
答案 0 :(得分:1)
我们可以避免清除数据库缓存。以下是我对上述问题的回答
public boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if(!dir.getAbsolutePath().contains("/yourDataBaseName")){
{
//clear all files except your database directory
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
}
// The directory is now empty so delete it
return dir.delete();
}