安卓清除快取、清除資料
阿新 • • 發佈:2019-01-09
清除資料主要是清除使用者配置,比如SharedPreferences、資料庫等等,這些資料都是在程式執行過程中儲存的使用者配置資訊,清除資料後,下次進入程式就和第一次進入程式時一樣
快取是程式執行時的臨時儲存空間,它可以存放從網路下載的臨時圖片,從使用者的角度出發清除快取對使用者並沒有太大的影響,但是清除快取後用戶再次使用該APP時,由於本地快取已經被清理,所有的資料需要重新從網路上獲取。為了在清除快取的時候能夠正常清除與應用相關的快取,請將快取檔案存放在getCacheDir()或者 getExternalCacheDir()路徑下。
/** * Created by Administrator on 2017/8/7. */ public class DataCleanManager { public static String getTotalCacheSize(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(Context context) { 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 < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } // 獲取檔案 //Context.getExternalFilesDir() --> 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 < fileList.length; i++) { // 如果下面還有檔案 if (fileList[i].isDirectory()) { size = size + getFolderSize(fileList[i]); } else { size = size + fileList[i].length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } /** * 格式化單位 * * @param size * @return */ public static String getFormatSize(double size) { double kiloByte = size / 1024; if (kiloByte < 1) { // return size + "Byte"; return "0K"; } double megaByte = kiloByte / 1024; if (megaByte < 1) { BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); return result1.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "KB"; } double gigaByte = megaByte / 1024; if (gigaByte < 1) { BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); return result2.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "MB"; } double teraBytes = gigaByte / 1024; if (teraBytes < 1) { BigDecimal result3 = new BigDecimal(Double.toString(gigaByte)); return result3.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "GB"; } BigDecimal result4 = new BigDecimal(teraBytes); return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"; } }
String totalCacheSize = DataCleanManager.getTotalCacheSize(getApplicationContext()); DataCleanManager.clearAllCache(getApplicationContext()); tv_cache.setText(DataCleanManager.getTotalCacheSize(getApplicationContext())); Toast.makeText(getApplicationContext(), "已為您清除" + totalCacheSize + "快取", Toast.LENGTH_SHORT).show();