• android 端缓存清理的实现


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

    先上图

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

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

  • 相关阅读:
    BZOJ 1977: [BeiJing2010组队]次小生成树 Tree( MST + 树链剖分 + RMQ )
    BZOJ 2134: 单选错位( 期望 )
    BZOJ 1030: [JSOI2007]文本生成器( AC自动机 + dp )
    BZOJ 2599: [IOI2011]Race( 点分治 )
    BZOJ 3238: [Ahoi2013]差异( 后缀数组 + 单调栈 )
    ZOJ3732 Graph Reconstruction Havel-Hakimi定理
    HDU5653 Bomber Man wants to bomb an Array 简单DP
    HDU 5651 xiaoxin juju needs help 水题一发
    HDU 5652 India and China Origins 并查集
    HDU4725 The Shortest Path in Nya Graph dij
  • 原文地址:https://www.cnblogs.com/android-zcq/p/5542946.html
Copyright © 2020-2023  润新知