2012-02-14 42 views

回答

0

最终我发现自己必须这样做,所以每次启动我的应用程序时都运行此清除缓存方法。

private static final long MIN_FREE_BYTES = 1024 * 1024 * 5; // this is 5M, Android recommend that there will always remind at last 1M 
    public static void cleareCache(File directory){ 
     if(directory == null){ 
      directory = AppGenManager.getInstance().getCacheDir(); 
     } 
     if(checkRemindingSpace(directory.getPath()) > MIN_FREE_BYTES){ 
      return; 
     } 

     File[] files = directory.listFiles(); 
     if (files != null) { 
      for (File file : files){ 
       if(file.isDirectory()){ 
        cleareCache(file); 
       } 
       else{ 
        file.delete(); 
       } 
      } 
     } 
    } 

    /** 
    * @param path file path 
    * @return the number of available bytes on this directory 
    */ 
    private static long checkRemindingSpace(String path){ 
     StatFs stat = new StatFs(path); 
     long blockSize = stat.getBlockSize(); 
     long availableBlocks = stat.getAvailableBlocks(); 
     return availableBlocks * blockSize; 
    }