APP开发中常有计算缓存大小和清空缓存的功能,此功能很常见,几乎每个应用都能看到,清除缓存功能算是个十分鸡肋的功能了,但是大多数产品或者客户都希望有这么个东西显得APP功能完善,网上有很多,但是对于新手来说,那些感觉并不详细,我贴个完整到小白都能懂的。
图1的界面代码我就不帖了,点击清除缓存,
findViewById(R.id.text_check).setOnClickListener(this);
case R.id.text_clear:
intent = new Intent(SettingActivity.this , ClearChcheActivity.class) ;
startActivity(intent);
break ;
图2,图3的界面代码如下:
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
import com.juronggvo.R;
import com.juronggvo.dialog.CustomDialog;
import com.juronggvo.loadimage.ImageFileCache;
import com.juronggvo.ui.BaseActivity;
import com.juronggvo.utils.DataCleanManager;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.TextView;
/**
* @description 清除缓存
* @data 2017年9月28日
* @author yang.yang
*/
public class ClearChcheActivity extends BaseActivity implements OnClickListener {
private CustomDialog.Builder ibuilder;
private TextView text_clear ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clear_chche);
init() ;
}
private void init(){
((TextView)findViewById(R.id.title)).setText("缓存管理");
findViewById(R.id.back).setOnClickListener(this);
text_clear = (TextView)this.findViewById(R.id.text_clear) ;
text_clear.setText(DataCleanManager.getFormatSize(ImageFileCache.calculateImageSize())+"");
text_clear.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.text_clear:
show() ;
break;
case R.id.back:
finish();
break;
default:
break;
}
}
private void show(){
ibuilder = new CustomDialog.Builder(ClearChcheActivity.this);
ibuilder.setTitle("清除缓存");
ibuilder.setMessage("清除缓存会导致下载的内容删除,是否确定?");
ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ImageFileCache.ClearCache() ;
showToast("缓存已清除");
text_clear.setText("0.0B");
dialog.dismiss();
}
});
Dialog dialog = ibuilder.create() ;
dialog.show();
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); //获取对话框当前的参数值
p.width = (int) (d.getWidth() * 0.8); //宽度设置为屏幕的0.9
dialog.getWindow().setAttributes(p); //设置生效
}
}
用到的几个类:首先是ImageFileCache类
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Comparator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
/**
* 文件缓存
*
* @author
*
*/
public class ImageFileCache {
// sd卡上的缓存文件夹
private static final String CACHDIR = "eduhighnanjing/imgCache/imgCache";
// 定义缓存文件后缀
private static final String WHOLESALE_CONV = ".cache";
// 缓存空间大小
private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 10;
// 规定的最大缓存
private static final int CACHE_SIZE = 10;
// 规定1MB大小
private static final int MB = 1024 * 1024;
// 设置缓存文件过期时间为10天
private static final long MTIMEDIFF = 10 * 24 * 60 * 60 * 1000;
public ImageFileCache() {
// 清理文件缓存
removeCache(getDirectory());
}
/**
* 根据url在图片缓存中得到图片
*
* @param url
* @return
*/
public Bitmap getImage(final String url) {
final String path = getDirectory() + "/" + convertUrlToFileName(url);
File file = new File(path);
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
if (bmp == null) {
file.delete();
} else {
// 更新图片最后修改时间
updateFileTime(path);
return bmp;
}
}
return null;
}
/**
* 将图片保存到sd卡
*
* @param bm
* @param url
*/
public void saveBmpToSd(Bitmap bm, String url) {
if (bm == null) {
// 需要保存的是一个空值
return;
}
// 判断sdcard上的空间
if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
// SD空间不足
return;
}
String filename = convertUrlToFileName(url);
String dir = getDirectory();
File file = new File(dir + "/" + filename);
try {
file.getParentFile().mkdirs();
file.createNewFile();
OutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
Log.w("ImageFileCache", "FileNotFoundException");
} catch (IOException e) {
Log.w("ImageFileCache", "IOException");
}
}
/**
* 计算存储目录下的文件大小,
* 当文件总大小大于规定的CACHE_SIZE或者sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规定
* 那么删除40%最近没有被使用的文件
*
* @param dirPath
* @param filename
*/
private boolean removeCache(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null) {
return true;
}
// 判断是否可操作sd卡
if (!android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return false;
}
// 计算出缓存文件总大小
int dirSize = 0;
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(WHOLESALE_CONV)) {
// 删除三天过期文件
removeExpiredCache(files[i]);
dirSize += files[i].length();
}
}
if (dirSize > CACHE_SIZE * MB
|| FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
// 删除百分之40
int removeFactor = (int) ((0.4 * files.length) + 1);
// 根据最后修改时间排序
Arrays.sort(files, new FileLastModifSort());
try {
Log.i("ImageFileCache", "清理缓存文件");
for (int i = 0; i < removeFactor; i++) {
if (files[i].getName().contains(WHOLESALE_CONV)) {
files[i].delete();
}
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
if (freeSpaceOnSd() <= CACHE_SIZE) {
return false;
}
return true;
}
/** * 根据文件的最后修改时间进行排序 */private class FileLastModifSort implements Comparator{
public int compare(File arg0, File arg1) {
if (arg0.lastModified() > arg1.lastModified()) {
return 1;
} else if (arg0.lastModified() == arg1.lastModified()) {
return 0;
} else {
return -1;
}
}
}
/**
* 删除超过三天的过期文件
*
* @param dirPath
* @param filename
*/
public void removeExpiredCache(File file) {
if (System.currentTimeMillis() - file.lastModified() > MTIMEDIFF) {
Log.i("ImageFileCache", "清除三天过期缓存文件");
file.delete();
}
}
/**
* 修改文件的最后修改时间 这里需要考虑,是否将使用的图片日期改为当前日期
*
* @param path
*/
public void updateFileTime(String path) {
File file = new File(path);
long newModifiedTime = System.currentTimeMillis();
file.setLastModified(newModifiedTime);
}
/**
* 计算sdcard上的剩余空间
*
* @return
*/
private int freeSpaceOnSd() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
.getBlockSize()) / MB;
return (int) sdFreeMB;
}
/**
* 将url转成文件名
*
* @param url
* @return
*/
private String convertUrlToFileName(String url) {
String[] strs = url.split("/");
return strs[strs.length - 1] + WHOLESALE_CONV;
}
/**
* 获得缓存目录
*
* @return
*/
private static String getDirectory() {
String dir = getSDPath() + "/" + CACHDIR;
String substr = dir.substring(0, 4);
if (substr.equals("/mnt")) {
dir = dir.replace("/mnt", "");
}
return dir;
}
/**
* 取SD卡路径
*
* @return
*/
public static String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
}
if (sdDir != null) {
return sdDir.toString();
} else {
return "";
}
}
public static String ClearCache() {
ImageMemoryCache.clear();
String clearResult1 = ClearFiles(getDirectory());
String clearResult2 = ClearFiles(ImageGetForHttp.getDirectory());
String result = "";
if (!clearResult1.equals("缓存清除成功") || !clearResult2.equals("缓存清除成功")) {
if (!clearResult1.equals("缓存清除成功")) {
result += clearResult1;
}
if (!clearResult2.equals("缓存清除成功") && !result.equals(clearResult1)) {
result += clearResult2;
}
} else {
result = "缓存清除成功";
}
return result;
}
private static String ClearFiles(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null) {
return "缓存清除成功";
}
// 判断是否可操作sd卡
if (!android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return "没有权限操作sd card";
}
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(WHOLESALE_CONV)) {
files[i].delete();
}
}
return "缓存清除成功";
}
public static long calculateImageSize() {
String dirPath = getDirectory();
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null) {
return 0;
}
// 判断是否可操作sd卡
if (!android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return 0;
}
// 计算出缓存文件总大小
int dirSize = 0;
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(WHOLESALE_CONV)) {
dirSize += files[i].length();
}
}
return dirSize;
}
}
然后就是DataCleanManager类
import java.io.File;
import java.math.BigDecimal;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
public class DataCleanManager {
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "B";
}
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() + "G";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
+ "T";
}
/**
* * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *
*
* @param context
*/
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/**
* * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *
*
* @param context
*/
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/databases"));
}
/**
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
*
* @param context
*/
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/shared_prefs"));
}
/**
* * 按名字清除本应用数据库 * *
*
* @param context
* @param dbName
*/
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/**
* * 清除/data/data/com.xxx.xxx/files下的内容 * *
*
* @param context
*/
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
*
* @param context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/**
* * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *
*
* @param filePath
* */
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* * 清除本应用所有的数据 * *
*
* @param context
* @param filepath
*/
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath == null) {
return;
}
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
*
* @param directory
*/
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.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 deleteThisPath
* @param filepath
* @return
*/
public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 如果下面还有文件
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是文件,删除
file.delete();
} else {// 目录
if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
file.delete();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
好了,基本就这样吧!
伟大的哲学家我自己曾经说过,有梦想就要大声说出来 ,万丈高楼平地起,能不能行靠自己!