iphone如何清理缓存一个activity的缓存

9259人阅读
Andriod开发(22)
现在很多APP中都有系统设置,这个模块中有一个缓存设置功能,用户可以查看当前APP缓存数据大小并且可以手动清空缓存数据。
缓存数据的统计分2块:内存(这里指的是应用程序包目录所在位置)+外存(外部存储卡)
我这里以开源中国APP数据缓存处理为例为大家讲解下
清除的目录包括:
1./data/data/package_name/files
2./data/data/package_name/cache
3.&sdcard&/Android/data/&package_name&/cache/
4.webview缓存数据
// 计算缓存大小
long fileSize = 0;
String cacheSize = &0KB&;
File filesDir = getFilesDir();// /data/data/package_name/files
File cacheDir = getCacheDir();// /data/data/package_name/cache
fileSize += getDirSize(filesDir);
fileSize += getDirSize(cacheDir);
// 2.2版本才有将应用缓存转移到sd卡的功能
if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
File externalCacheDir = getExternalCacheDir(this);//&&sdcard&/Android/data/&package_name&/cache/&
fileSize += getDirSize(externalCacheDir);
if (fileSize & 0)
cacheSize = formatFileSize(fileSize);
* 获取目录文件大小
* @param dir
public static long getDirSize(File dir) {
if (dir == null) {
if (!dir.isDirectory()) {
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 dirS
* 判断当前版本是否兼容目标版本的方法
* @param VersionCode
public static boolean isMethodsCompat(int VersionCode) {
int currentVersion = android.os.Build.VERSION.SDK_INT;
return currentVersion &= VersionC
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
// return context.getExternalCacheDir(); API level 8
// e.g. &&sdcard&/Android/data/&package_name&/cache/&
return context.getExternalCacheDir();
* 转换文件大小
* @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 & ) {
fileSizeString = df.format((double) fileS / 1048576) + &MB&;
fileSizeString = df.format((double) fileS / ) + &G&;
return fileSizeS
* 清除app缓存
* @param activity
public static void clearAppCache(Activity activity) {
final AppContext ac = (AppContext) activity.getApplication();
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
ToastMessage(ac, &缓存清除成功&);
ToastMessage(ac, &缓存清除失败&);
new Thread() {
public void run() {
Message msg = new Message();
ac.clearAppCache();
msg.what = 1;
} catch (Exception e) {
e.printStackTrace();
msg.what = -1;
handler.sendMessage(msg);
}.start();
在项目中经常会使用到WebView 控件,当加载html 页面时,会在/data/data/package_name目录下生成database与cache 两个文件夹。请求的url 记录是保存在WebViewCache.db,而url 的内容是保存在WebViewCache 文件夹下
* 清除app缓存
public void clearAppCache()
//清除webview缓存
@SuppressWarnings(&deprecation&)
File file = CacheManager.getCacheFileBaseDir();
//先删除WebViewCache目录下的文件
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete();
file.delete();
deleteDatabase(&webview.db&);
deleteDatabase(&webview.db-shm&);
deleteDatabase(&webview.db-wal&);
deleteDatabase(&webviewCache.db&);
deleteDatabase(&webviewCache.db-shm&);
deleteDatabase(&webviewCache.db-wal&);
//清除数据缓存
clearCacheFolder(getFilesDir(),System.currentTimeMillis());
clearCacheFolder(getCacheDir(),System.currentTimeMillis());
//2.2版本才有将应用缓存转移到sd卡的功能
if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
clearCacheFolder(getExternalCacheDir(this),System.currentTimeMillis());
* 清除缓存目录
* @param dir 目录
* @param numDays 当前系统时间
private int clearCacheFolder(File dir, long curTime) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
for (File child:dir.listFiles()) {
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, curTime);
if (child.lastModified() & curTime) {
if (child.delete()) {
deletedFiles++;
} catch(Exception e) {
e.printStackTrace();
return deletedF
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:36245次
排名:千里之外
原创:22篇
(18)(4)(7)(1)首先关于缓存清理,网上已经有太多的工具类,但是遗憾的是,基本上都不完善,或者说根本就不能用,而项目中又要求实现这个烂东西(其实这玩意真没一点屁用,毕竟第三方清理/杀毒软件都带这么一个功能),但是只好硬着头皮搞搞.. 随记录如下:
当点击清理缓存 这个LinearLayout 弹出对话框,
case R.id.rl_clean_cache://清理缓存
onClickCleanCache();
//------****** 缓存相关****----------
private final int CLEAN_SUC=1001;
private final int CLEAN_FAIL=1002;
private void onClickCleanCache() {
getConfirmDialog(getActivity(), "是否清空缓存?", new DialogInterface.OnClickListener
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);
public static AlertDialog.Builder getDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
* 计算缓存的大小
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 &= VersionC
* 清除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缓存
public void clearAppCache() {
new Thread() {
public void run() {
Message msg = new Message();
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(),"清除失败");
case CLEAN_SUC:
ToastUtils.show(SxApplication.getInstance(),"清除成功");
以上代码位于一个 fragment中,代码中用到了2个工具如下所示:
* 应用程序配置类:用于保存用户相关信息及设置
public class AppConfig {
private final static String APP_CONFIG = "config";
private Context mC
private static AppConfig appC
public static AppConfig getAppConfig(Context context) {
if (appConfig == null) {
appConfig = new AppConfig();
appConfig.mContext =
return appC
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();
// 读取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 {
fis.close();
} catch (Exception e) {
private void setProps(Properties p) {
FileOutputStream fos = null;
// 把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 {
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);
* 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 extCacheD
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
public static long getDirSize(File dir) {
if (dir == null) {
if (!dir.isDirectory()) {
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 dirS
* 转换文件大小
* @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 & ) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
fileSizeString = df.format((double) fileS / ) + "G";
return fileSizeS
以上就是缓存清理了,完美搞定!
阅读(...) 评论()liushaodong 的BLOG
用户名:liushaodong
文章数:19
访问量:16173
注册日期:
阅读量:5863
阅读量:12276
阅读量:357666
阅读量:1054206
51CTO推荐博文
备忘:清理软件缓存功能的代码个人测试了第二种方法,是有效果的清理软件缓存一种带root权限的:Class c1 = Class.forName("android.content.pm.IPackageDataObserver");Method method = pm.getClass().getMethod("deleteApplicationCacheFiles", String.class,IPackageDataObserver.class);method.invoke(pm, packageName,new IPackageDataObserver.Stub(){@Overridepublic void onRemoveCompleted(String packageName,boolean succeeded) throws RemoteException {// TODO Auto-generated method stub}});&uses-permission android:name="android.permission.DELETE_CACHE_FILES" /&另外一种是不用root权限;一键清理:权限:&uses-permission android:name="android.permission.CLEAR_APP_CACHE" /&private static long getEnvironmentSize() {
File localFile = Environment.getDataDirectory();
if (localFile == null)
String str = localFile.getPath();
StatFs localStatFs = new StatFs(str);
long l2 = localStatFs.getBlockSize();
l1 = localStatFs.getBlockCount() * l2;
return l1;
public static void clear(Activity activity) {
PackageManager pm = activity.getPackageManager();
Method localMethod = pm.getClass().getMethod("freeStorageAndNotify", Long.TYPE, IPackageDataObserver.class);
Long localLong = Long.valueOf(getEnvironmentSize() - 1L);
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = localL
localMethod.invoke(pm, localLong, new IPackageDataObserver.Stub() {
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
Log.e("onRemoveCompleted,packageName="+packageName+",succeeded="+succeeded);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}可能会遇到IPackageDataObserver这个无法导进去,自己写一个IPackageDataObserver.aidl,内容如下:package android.content. /**
&* API for package data change related callbacks from the Package Manager.
&* Some usage scenarios include deletion of cache directory, generate
&* statistics related to code, data, cache usage(TODO)
&*/ oneway interface IPackageDataObserver {
& & void onRemoveCompleted(in String packageName, boolean succeeded); }放在src包下就行了。
了这篇文章
类别:未分类┆阅读(0)┆评论(0)

我要回帖

更多关于 如何清理浏览器缓存 的文章

 

随机推荐