首先关于缓存清理,网上已经有太多的工具类,但是遗憾的是,基本上都不完善,或者说根本就不能用,而项目中又要求实现这个烂东西(其实这玩意真没一点屁用,毕竟第三方清理/杀毒软件都带这么一个功能),但是只好硬着头皮搞搞.. 随记录如下:

先上图

当点击清理缓存 这个LinearLayout 弹出对话框,

代码如下:

 case R.id.rl_clean_cache://清理缓存
onClickCleanCache();
break;
//------****** 缓存相关****----------
private final int CLEAN_SUC=1001;
private final int CLEAN_FAIL=1002;
private void onClickCleanCache() {
getConfirmDialog(getActivity(), "是否清空缓存?", new DialogInterface.OnClickListener
() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
clearAppCache();
tvCache.setText("0KB");
}
}).show();
}
public static AlertDialog.Builder getConfirmDialog(Context context, String message, DialogInterface.OnClickListener onClickListener) {
AlertDialog.Builder builder = getDialog(context);
builder.setMessage(Html.fromHtml(message));
builder.setPositiveButton("确定", onClickListener);
builder.setNegativeButton("取消", null);
return builder;
}
public static AlertDialog.Builder getDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
return builder;
}
/**
* 计算缓存的大小
*/
private void caculateCacheSize() {
long fileSize = 0;
String cacheSize = "0KB";
File filesDir = getActivity().getFilesDir();
File cacheDir = getActivity().getCacheDir(); fileSize += FileUtil.getDirSize(filesDir);
fileSize += FileUtil.getDirSize(cacheDir);
// 2.2版本才有将应用缓存转移到sd卡的功能
if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
File externalCacheDir = MethodsCompat
.getExternalCacheDir(getActivity());
fileSize += FileUtil.getDirSize(externalCacheDir);
fileSize += FileUtil.getDirSize(new File(
org.kymjs.kjframe.utils.FileUtils.getSDCardPath()
+ File.separator + "KJLibrary/cache"));
}
if (fileSize > 0)
cacheSize = FileUtil.formatFileSize(fileSize);
tvCache.setText(cacheSize);
} public static boolean isMethodsCompat(int VersionCode) {
int currentVersion = android.os.Build.VERSION.SDK_INT;
return currentVersion >= VersionCode;
}
/**
* 清除app缓存
*/
public void myclearaAppCache() {
DataCleanManager.cleanDatabases(getActivity());
// 清除数据缓存
DataCleanManager.cleanInternalCache(getActivity());
// 2.2版本才有将应用缓存转移到sd卡的功能
if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
DataCleanManager.cleanCustomCache(MethodsCompat
.getExternalCacheDir(getActivity()));
}
// 清除编辑器保存的临时内容
Properties props = getProperties();
for (Object key : props.keySet()) {
String _key = key.toString();
if (_key.startsWith("temp"))
removeProperty(_key);
}
Core.getKJBitmap().cleanCache();
} /**
* 清除保存的缓存
*/
public Properties getProperties() {
return AppConfig.getAppConfig(getActivity()).get();
}
public void removeProperty(String... key) {
AppConfig.getAppConfig(getActivity()).remove(key);
}
/**
* 清除app缓存
*
* @param
*/
public void clearAppCache() { new Thread() {
@Override
public void run() {
Message msg = new Message();
try {
myclearaAppCache();
msg.what = CLEAN_SUC;
} catch (Exception e) {
e.printStackTrace();
msg.what = CLEAN_FAIL;
}
handler.sendMessage(msg);
}
}.start();
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CLEAN_FAIL:
ToastUtils.show(SxApplication.getInstance(),"清除失败");
break;
case CLEAN_SUC:
ToastUtils.show(SxApplication.getInstance(),"清除成功");
break;
}
};
};

以上代码位于一个 fragment中,代码中用到了2个工具如下所示:

工具1:

/**
* 应用程序配置类:用于保存用户相关信息及设置
*/
public class AppConfig { private final static String APP_CONFIG = "config"; private Context mContext;
private static AppConfig appConfig; public static AppConfig getAppConfig(Context context) {
if (appConfig == null) {
appConfig = new AppConfig();
appConfig.mContext = context;
}
return appConfig;
} public String get(String key) {
Properties props = get();
return (props != null) ? props.getProperty(key) : null;
} public Properties get() {
FileInputStream fis = null;
Properties props = new Properties();
try {
// 读取files目录下的config
// fis = activity.openFileInput(APP_CONFIG);
// 读取app_config目录下的config
File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
fis = new FileInputStream(dirConf.getPath() + File.separator
+ APP_CONFIG); props.load(fis);
} catch (Exception e) {
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return props;
} private void setProps(Properties p) {
FileOutputStream fos = null;
try {
// 把config建在files目录下
// fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE); // 把config建在(自定义)app_config的目录下
File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
File conf = new File(dirConf, APP_CONFIG);
fos = new FileOutputStream(conf); p.store(fos, null);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
} public void set(Properties ps) {
Properties props = get();
props.putAll(ps);
setProps(props);
} public void set(String key, String value) {
Properties props = get();
props.setProperty(key, value);
setProps(props);
} public void remove(String... key) {
Properties props = get();
for (String k : key)
props.remove(k);
setProps(props);
}
}

工具2:

/**
* Android各版本的兼容方法
*/
public class MethodsCompat { @TargetApi(5)
public static void overridePendingTransition(Activity activity, int enter_anim, int exit_anim) {
activity.overridePendingTransition(enter_anim, exit_anim);
} @TargetApi(7)
public static Bitmap getThumbnail(ContentResolver cr, long origId, int kind, Options options) {
return MediaStore.Images.Thumbnails.getThumbnail(cr,origId,kind, options);
} @TargetApi(8)
public static File getExternalCacheDir(Context context) { // // return context.getExternalCacheDir(); API level 8
//
// // e.g. "<sdcard>/Android/data/<package_name>/cache/"
// final File extCacheDir = new File(Environment.getExternalStorageDirectory(),
// "/Android/data/" + context.getApplicationInfo().packageName + "/cache/");
// extCacheDir.mkdirs();
// return extCacheDir; return context.getExternalCacheDir();
} @TargetApi(11)
public static void recreate(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
activity.recreate();
}
} @TargetApi(11)
public static void setLayerType(View view, int layerType, Paint paint) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
view.setLayerType(layerType, paint);
}
} @TargetApi(14)
public static void setUiOptions(Window window, int uiOptions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
window.setUiOptions(uiOptions);
}
}

还有FileUtil类

public class FileUtil {
/**
* 获取目录文件大小
*
* @param dir
* @return
*/
public static long getDirSize(File dir) {
if (dir == null) {
return 0;
}
if (!dir.isDirectory()) {
return 0;
}
long dirSize = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
dirSize += file.length();
} else if (file.isDirectory()) {
dirSize += file.length();
dirSize += getDirSize(file); // 递归调用继续统计
}
}
return dirSize;
} /**
* 转换文件大小
*
* @param fileS
* @return B/KB/MB/GB
*/
public static String formatFileSize(long fileS) {
java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
}

以上就是缓存清理了,完美搞定!

最新文章

  1. HTML 5 胜出:XHTML2 宣告夭折
  2. C++的STL
  3. CentOS彻底卸载wine
  4. XCode升级导致的IAP失败的问题
  5. 关于COUNT STOPKEY的工作机制(转载)
  6. 解决网站出错后 跳转 友好页面 的 asp .net 配置
  7. 20151215jqueryUI--dialog代码备份
  8. poj 3579 Median (二分搜索之查找第k大的值)
  9. hdu 4740
  10. 修改NavigationBar样式
  11. webstorm 激活码
  12. Oracle分析函数——函数列表
  13. Spring Boot的事务处理
  14. log4j-日志记录小结
  15. Shell编程(四)Shell变量
  16. 基于 ASP.NET Core 2.1 的 Razor Class Library 实现自定义错误页面的公用类库
  17. C语言复习---用筛选法求100之内的素数
  18. Spark2 Linear Regression线性回归
  19. 自定义iconfont 图标库下载本地在移动App的使用及svg彩色图标
  20. win7下使用手动安装composer

热门文章

  1. 关于 IntelliJ 的 IDEA PyCharm 等更新 2019.2 后中文乱码 的解决方案
  2. -bash: redis: command not found
  3. React单页面应用使用antd的锚点跳转失效
  4. 实现API管理系统的几个重要关键词
  5. 11.源码分析---SOFARPC数据透传是实现的?
  6. 你是否真的了解全局解析锁(GIL)
  7. 第一章 .NET基础-C#基础
  8. 【翻译】无需安装Python,就可以在.NET里调用Python库
  9. OSG与Shader的结合使用
  10. java日志框架笔记-log4j-springboot整合