天天看點

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.     }