1
 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();
   }
}

我正在使用上面的代码来清除我的缓存,但这也会删除我的数据库更新。如何在不影响数据库更新的情况下只清除缓存(图像缓存)?

4

1 回答 1

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();

}

于 2013-08-23T03:36:29.087 回答