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

先上图

当点击清理缓存 这个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;
}
}

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

android 端缓存清理的实现的更多相关文章

  1. Android Glide数据更新及内存缓存、硬盘缓存清理

    [转] 原文                                         Android Glide数据更新及内存缓存.硬盘缓存清理 Android的Glide在加载图片时候内部默 ...

  2. Android图片缓存之Lru算法

    前言: 上篇我们总结了Bitmap的处理,同时对比了各种处理的效率以及对内存占用大小.我们得知一个应用如果使用大量图片就会导致OOM(out of memory),那该如何处理才能近可能的降低oom发 ...

  3. Android图片缓存之初识Glide

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实 ...

  4. Android端上传图片到后台,存储到数据库中 详细代码

    首先点击头像弹出popwindow,点击相册,相机,调用手机自带的裁剪功能,然后异步任务类访问服务器,上传头像,保存到数据库中, 下面写出popwindow的代码 //设置popwindow publ ...

  5. Android ListView分页载入(服务端+android端)Demo

    Android ListView分页载入功能 在实际开发中经经常使用到,是每一个开发人员必须掌握的内容,本Demo给出了服务端+Android端的两者的代码,并成功通过了測试. 服务端使用MyEcli ...

  6. 安卓高级 Android图片缓存之初识Glide

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实 ...

  7. JMessage Android 端开发详解

    目前越来越多的应用会需要集成即时通讯功能,这里就为大家详细讲一下如何通过集成 JMessage 来为你的 App 增加即时通讯功能. 首先,一个最基础的 IM 应用会需要有哪些功能? 用户注册 / 登 ...

  8. Android图片缓存之Lru算法(二)

    前言: 上篇我们总结了Bitmap的处理,同时对比了各种处理的效率以及对内存占用大小.我们得知一个应用如果使用大量图片就会导致OOM(out of memory),那该如何处理才能近可能的降低oom发 ...

  9. 短视频技术详解:Android端的短视频开发技术

    在 <如何快速实现移动端短视频功能?>中,我们主要介绍了当前短视频的大热趋势以及开发一个短视频应用所涉及到的功能和业务.在本篇文章中,我们主要谈一谈短视频在Android端上的具体实现技术 ...

随机推荐

  1. Python 面向導向語言 Object Oriented Programming Language

    Pytho 是面向對象的程式語言,舉凡 Literals 值都是 Object.例如: >>> id(38)8791423739696 與 >>> id('ABC' ...

  2. print,cat打印格式及字符串引号格式,去掉字符串空格 in R

    print 函数的打印格式: ##no quote print out > x <- letters[1:5] > print(x,quote=F,);print(x,quote=T ...

  3. 类spring ioc 泛型保留

    类spring ioc 泛型保留 什么是泛型擦除 Java并不会传递泛型类,举个直观的栗子: @Component public class BaseProvider<T> { publi ...

  4. 盘一盘 NIO (三)—— Selector解析

    Selector是个啥? Selector是Java NIO核心组件中的选择器,用于检查一个或多个Channel(通道)的状态是否处于可读.可写.实现一个单独的线程可以管理多个channel,从而管理 ...

  5. MyBatis的parameterType传入参数类型

    在mybatis映射接口的配置中,有select,insert,update,delete等元素都提到了parameterType的用法,parameterType为输入参数,在配置的时候,配置相应的 ...

  6. java短信验证和注册

    最近公司需要用到短信验证注册,所以申请了阿里云的短信服务.我的项目是分布式的spring boot 原理: 利用第三方发送短信 获取回执消息,然后存入缓存里面 将用户填写的验证码与缓存里面的验证码对比 ...

  7. cookies和sessionstorage和localstorage区别

    相同点:客户端都会存储 不同点 不同点 存储大小 有效时间 数据与服务器交互方式 cookies <=4K 在设置cookie过期之前一直有效(无论窗口浏览器是否关闭) 正常情况下,cookie ...

  8. XMLHttpRequest的概述

    XMLHttpRequest的概述 一.前言 XMLHttpRequest 最早是在IE5中以ActiveX组件的形式实现的.非 W3C 标准. 创建XMLHttpRequest对象(由于非标准所以实 ...

  9. Delphi - Indy TIdFTP控件实现文件的上传和下载

    FTP信息保存和获取 我们在做FTP相关开发时,为方便后续FTP切换,一般先把FTP账户信息保存到数据库表中,在使用时再通过Query获取出来. 一般通过如下方式获取到FTP相关信息,代码如下: // ...

  10. spring-cloud-kubernetes背后的三个关键知识点

    在<你好spring-cloud-kubernetes>一文中,对spring-cloud-kubernetes这个SpringCloud官方kubernetes服务框架有了基本了解,今天 ...