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

先上图

当点击清理缓存 这个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. Flink 源码解析 —— 如何获取 JobGraph?

    JobGraph https://t.zsxq.com/naaMf6y 博客 1.Flink 从0到1学习 -- Apache Flink 介绍 2.Flink 从0到1学习 -- Mac 上搭建 F ...

  2. JavaScript数据结构——队列的实现与应用

    队列与栈不同,它遵从先进先出(FIFO——First In First Out)原则,新添加的元素排在队列的尾部,元素只能从队列头部移除. 我们在前一篇文章中描述了如何用JavaScript来实现栈这 ...

  3. 史上最全面 Android逆向培训之__Xposed使用

    刚招来个Android,干了半个月辞职了,他走之后,成堆的bug被测了出来,都是这个新人代码都没看懂就开始改的一塌糊涂,还给提交了.实在是让人头疼,清理了一个月多月才把他半个月写的bug清理个差不多. ...

  4. 一段代码分清global和nonlocal

    废话不多说,直接代码啊~~~ a=999 b=99999 def test1(): a=888 b=88888 print('a={}'.format(a)) print('b={}'.format( ...

  5. java后端_百度二面

    参考: https://www.nowcoder.com/discuss/215891?type=2&order=0&pos=10&page=1 1. gc 2. java l ...

  6. PostgreSQL创建扩展出错

    问题: loraserver_as=# create extension pg_trgm; ERROR: could not open extension control file "/us ...

  7. Python模块之netmiko

    一.简介 此模块用于简化paramiko与网络设备之间的ssh连接,可在windows与Unix平台使用 二.目前支持的设备 (2019.03.07) Regularly tested Arista ...

  8. C#中appium自动化执行移动命令mobile:shell用法

    官网:https://appium.readthedocs.io/en/latest/en/commands/mobile-command/#android 1.执行ADB shell命令(需要设置服 ...

  9. peewee

    字段查看http://docs.peewee-orm.com/en/latest/peewee/models.html#fields 方法使用https://blog.csdn.net/qq_3962 ...

  10. 新手学习selenium路线图(老司机亲手绘制)

    前言: 最近群里有不少小白,想入手selenium,但是一直没找到学习路线,还没入门就迷路了,于是小编亲手绘制了一幅学习路线图.希望能帮助小白快速入门,帮助已经入门的,尽快提升! 学习selenium ...