天天看点

android APP清除缓存功能

现在很多APP中都有系统设置,这个模块中有一个缓存设置功能,用户可以查看当前APP缓存数据大小并且可以手动清空缓存数据。

缓存数据的统计分2块:内存(这里指的是应用程序包目录所在位置)+外存(外部存储卡)

我这里以开源中国APP数据缓存处理为例为大家讲解下

清除的目录包括:

1./data/data/package_name/files

2./data/data/package_name/cache

3.<sdcard>/Android/data/<package_name>/cache/

4.webview缓存数据

[plain]  view plain copy print ?

  1. // 计算缓存大小  
  2.         long fileSize = 0;  
  3.         String cacheSize = "0KB";  
  4.         File filesDir = getFilesDir();// /data/data/package_name/files  
  5.         File cacheDir = getCacheDir();// /data/data/package_name/cache  
  6.         fileSize += getDirSize(filesDir);  
  7.         fileSize += getDirSize(cacheDir);  
  8. // 2.2版本才有将应用缓存转移到sd卡的功能  
  9.         if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){  
  10.             File externalCacheDir = getExternalCacheDir(this);//"<sdcard>/Android/data/<package_name>/cache/"  
  11.             fileSize += getDirSize(externalCacheDir);             
  12.         }  
  13.        if (fileSize > 0)  
  14.             cacheSize = formatFileSize(fileSize);  
  15.     public static long getDirSize(File dir) {  
  16.         if (dir == null) {  
  17.             return 0;  
  18.         }  
  19.         if (!dir.isDirectory()) {  
  20.             return 0;  
  21.         }  
  22.         long dirSize = 0;  
  23.         File[] files = dir.listFiles();  
  24.         for (File file : files) {  
  25.             if (file.isFile()) {  
  26.                 dirSize += file.length();  
  27.             } else if (file.isDirectory()) {  
  28.                 dirSize += file.length();  
  29.                 dirSize += getDirSize(file); // 递归调用继续统计  
  30.             }  
  31.         }  
  32.         return dirSize;  
  33.     }  
  34.     public static boolean isMethodsCompat(int VersionCode) {  
  35.         int currentVersion = android.os.Build.VERSION.SDK_INT;  
  36.         return currentVersion >= VersionCode;  
  37.     }  
  38. @TargetApi(8)  
  39.     public static File getExternalCacheDir(Context context) {  
  40.        // return context.getExternalCacheDir(); API level 8  
  41.         // e.g. "<sdcard>/Android/data/<package_name>/cache/"  
  42.         return context.getExternalCacheDir();  
  43.     }  
  44.     public static String formatFileSize(long fileS) {  
  45.         java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");  
  46.         String fileSizeString = "";  
  47.         if (fileS < 1024) {  
  48.             fileSizeString = df.format((double) fileS) + "B";  
  49.         } else if (fileS < 1048576) {  
  50.             fileSizeString = df.format((double) fileS / 1024) + "KB";  
  51.         } else if (fileS < 1073741824) {  
  52.             fileSizeString = df.format((double) fileS / 1048576) + "MB";  
  53.         } else {  
  54.             fileSizeString = df.format((double) fileS / 1073741824) + "G";  
  55.         }  
  56.         return fileSizeString;  
  57.     }  
  58.     public static void clearAppCache(Activity activity) {  
  59.         final AppContext ac = (AppContext) activity.getApplication();  
  60.         final Handler handler = new Handler() {  
  61.             public void handleMessage(Message msg) {  
  62.                 if (msg.what == 1) {  
  63.                     ToastMessage(ac, "缓存清除成功");  
  64.                 } else {  
  65.                     ToastMessage(ac, "缓存清除失败");  
  66.                 }  
  67.             }  
  68.         };  
  69.         new Thread() {  
  70.             public void run() {  
  71.                 Message msg = new Message();  
  72.                 try {  
  73.                     ac.clearAppCache();  
  74.                     msg.what = 1;  
  75.                 } catch (Exception e) {  
  76.                     e.printStackTrace();  
  77.                     msg.what = -1;  
  78.                 }  
  79.                 handler.sendMessage(msg);  
  80.             }  
  81.         }.start();  
  82.     }  
  83. 在项目中经常会使用到WebView 控件,当加载html 页面时,会在/data/data/package_name目录下生成database与cache 两个文件夹。请求的url 记录是保存在WebViewCache.db,而url 的内容是保存在WebViewCache 文件夹下  
  84.     public void clearAppCache()  
  85.     {  
  86.         //清除webview缓存  
  87.         @SuppressWarnings("deprecation")  
  88.         File file = CacheManager.getCacheFileBaseDir();   
  89.        //先删除WebViewCache目录下的文件  
  90.         if (file != null && file.exists() && file.isDirectory()) {    
  91.             for (File item : file.listFiles()) {    
  92.                 item.delete();    
  93.             }    
  94.             file.delete();    
  95.         }              
  96.         deleteDatabase("webview.db");    
  97.         deleteDatabase("webview.db-shm");    
  98.         deleteDatabase("webview.db-wal");    
  99.         deleteDatabase("webviewCache.db");    
  100.         deleteDatabase("webviewCache.db-shm");    
  101.         deleteDatabase("webviewCache.db-wal");    
  102.         //清除数据缓存  
  103.         clearCacheFolder(getFilesDir(),System.currentTimeMillis());  
  104.         clearCacheFolder(getCacheDir(),System.currentTimeMillis());  
  105.         //2.2版本才有将应用缓存转移到sd卡的功能  
  106.         if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){  
  107.             clearCacheFolder(getExternalCacheDir(this),System.currentTimeMillis());  
  108.         }  
  109.     }      
  110.     private int clearCacheFolder(File dir, long curTime) {            
  111.         int deletedFiles = 0;           
  112.         if (dir!= null && dir.isDirectory()) {               
  113.             try {                  
  114.                 for (File child:dir.listFiles()) {      
  115.                     if (child.isDirectory()) {                
  116.                         deletedFiles += clearCacheFolder(child, curTime);            
  117.                     }    
  118.                     if (child.lastModified() < curTime) {       
  119.                         if (child.delete()) {                     
  120.                             deletedFiles++;             
  121.                         }      
  122.                     }      
  123.                 }               
  124.             } catch(Exception e) {         
  125.                 e.printStackTrace();      
  126.             }       
  127.         }         
  128.         return deletedFiles;       
  129.     }