项目中碰到了计算缓存大小和清空缓存的功能,这个很常见的功能,几乎每个APP都有,以为实现很简单,网上搜了一大堆,发现都不是符合我需要的,而且经常删除的没有效果,于是又另外找了一些资料,折腾了蛮久,终于完成了。以下的这个类的功能很简单,计算你的缓存总大小,不管内部缓存还是外部缓存,和清空缓存,包括内部和外部的缓存一起清空:

publicclass DataCleanManager {         public static StringgetTotalCacheSize(Context context) throws Exception {            long cacheSize =getFolderSize(context.getCacheDir());            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                 cacheSize +=getFolderSize(context.getExternalCacheDir());            }             return getFormatSize(cacheSize);        }      public static void clearAllCache(Contextcontext) {        deleteDir(context.getCacheDir());        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            deleteDir(context.getExternalCacheDir());        }     }      private static boolean deleteDir(File dir){        if (dir != null &&dir.isDirectory()) {            String[] children = dir.list();            for (int i = 0; i 
SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据     //Context.getExternalCacheDir() -->SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据     public static long getFolderSize(File file)throws Exception {         long size = 0;         try {             File[] fileList =file.listFiles();             for (int i = 0; i 

当你在项目中需要查下缓存大小,就使用getTotalCacheSize(Context)方法,清空缓存,就使用clearAllCache(Context)方法。当然,开发完APP也是需要进行全方位的检测: