Android 获得本应用的缓存和清除缓存的代码实例
程序员文章站
2023-10-12 20:46:22
android 获得本应用的缓存和清除缓存的代码实例
package com.luoy.blocklover.common.untils;
import android.content.c...
android 获得本应用的缓存和清除缓存的代码实例
package com.luoy.blocklover.common.untils; import android.content.context; import android.os.environment; import java.io.file; import java.math.bigdecimal; /** * created by luoy on 2018/7/24 0024. */ public class datacleanmanager {/** * 获取缓存大小 * @param context * @return * @throws exception */ 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); } /** * 清除缓存 * @param context */ 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() + "k"; } double gigabyte = megabyte / 1024; if (gigabyte < 1) { bigdecimal result2 = new bigdecimal(double.tostring(megabyte)); return result2.setscale(2, bigdecimal.round_half_up) .toplainstring() + "m"; } 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"; } }