清除缓存功能_externaldiskcache作用-程序员宅基地

技术标签: 清除缓存  Glide清除缓存  Android  

清除缓存的功能在app中还是经常可以碰到的,虽然实现起来很容易,但每次做的时候都还是得上网搜一把,还是自己总结一下。

思路:(额...还真算不上什么思路...就一句话)

点击清理缓存,调用清除缓存的方法,并弹清除缓存进度条,当缓存的大小等于0的时候,隐藏进度条,并吐司“缓存清理完毕”。

app展示:


主要代码:(只展示清除图片的缓存,其他类似)

private void showIOSActionSheetDialog() {
    new IOSActionSheetDialog(mActivity)
            .builder()
            .setTitle("清除缓存后,可以释放内存,但所有的数据得重新加载,确定要清除缓存?")
            .setCancelable(false)
            .setCanceledOnTouchOutside(false)
            .addSheetItem("清除缓存", IOSActionSheetDialog.SheetItemColor.Red,
                    new IOSActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            mActivity.showDialog("正在清除缓存...", true);
                            ThreadUtil.runOnSubThread(new Runnable() {
                                @Override
                                public void run() {
                                    GlideCacheUtil.getInstance().clearImageAllCache(mActivity);
                                    ThreadUtil.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            adapter.notifyDataSetChanged();
                                            adapter.setOnCacheClearFinishListener(new PersonalCenterRecyclerViewAdapter.onCacheClearFinishListener() {
                                                @Override
                                                public void onCacheClearFinish(String cacheSize) {
                                                    if (cacheSize.equals(NONE_CACHE)) {
                                                        mActivity.hideDialog();
                                                        mActivity.showToast("缓存清理完毕");
                                                    }
                                                }
                                            });

                                        }
                                    });
                                }
                            });
                        }
                    }).show();
}
主要的工具类:

Glide工具类:

public class GlideCacheUtil {
    private static GlideCacheUtil inst;

    public static GlideCacheUtil getInstance() {
        if (inst == null) {
            inst = new GlideCacheUtil();
        }
        return inst;
    }

    /**
     * 清除图片磁盘缓存
     */
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
                        // BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存
     */
    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片所有缓存
     */
    public void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String ImageExternalCatchDir=context.getExternalCacheDir()+ ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        deleteFolderFile(ImageExternalCatchDir, true);
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/"+ InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件,这里用于缓存的删除
     *
     * @param filePath filePath
     * @param deleteThisPath deleteThisPath
     */
    private void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }
}

普通文件、数据工具类:

public class DataCleanUtil {
    /**
     * * 清除本应用内部缓存(/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;
    }

    /**
     * 删除指定目录下文件及目录
     */
    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();
            }
        }
    }

    /**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }
}
有这两个工具类,就可以清除你想清除的缓存了。


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Android_xue/article/details/78285452

智能推荐

automapper自动创建映射,使用AutoMapper映射子集合-程序员宅基地

文章浏览阅读222次。I am using Automapper for making a copy of an objectMy domain can be reduced into this following exampleConsider I have a Store with a collection of Locationpublic class Store{public string Name { get..._automapper 子集合

第九章 SpringBoot缓存-方法的缓存❤❤

基于Ehcache或Redis通过注解Cacheable,CachePut及CacheEvict实现

Baumer工业相机堡盟工业相机如何通过BGAPISDK进行定序器编程:根据每次触发信号移动感兴趣区域(C#)-程序员宅基地

文章浏览阅读242次。Baumer工业相机堡盟工业相机如何通过BGAPISDK进行定序器编程:根据每次触发信号移动感兴趣区域(C#)

zabbix部署及监控测试_zabbix活动服务器地址-程序员宅基地

文章浏览阅读1.1k次,点赞3次,收藏15次。文章目录环境准备部署配置server部署配置webUI部署配置agent监控测试环境准备准备虚拟机192.168.90.30 zabbixserver zbxserver.com centos7 3G 50G zabbix server 即webUI所在的服务器192.168.90.20 zabbixagent mysql.com centos7 3G 50G mysql服务器即 zabbixagent 所在的服务器配置域名:两台服务器分别配置host[root@loca_zabbix活动服务器地址

ES全文检索支持拼音和繁简检索

介绍了在 Elasticsearch 中实现全文检索支持拼音和繁简检索的步骤。首先,介绍了如何引入 pinyin 插件和 ik 分词器插件,包括编译和安装的过程。然后,讲解了建立索引的步骤,包括设置文件和字段映射文件的配置。接着,提供了测试检索的方法和结果展示,包括中文简体、繁体查询以及拼音全拼和简拼查询。最后,还介绍了繁简转换功能的配置。整篇文档详细说明了每个步骤的操作,为实现全文检索功能提供了指导。

使用xshell工具连接ubuntu的root账户被拒绝的解决方法

详细介绍了使用xshell工具连接ubuntu系统的root用户时,被拒绝的问题。

随便推点

如何在Linux服务器上安装Stable Diffusion WebUI

如何在Linux服务器上安装Stable Diffusion WebUI

Stable Diffusion一键安装包启动疑难报错解析:Python 无法找到模块‘urlib’以及其他报错的解决方法

如果您遇到 ModuleNotFoundError: No module named ‘_socket’ 错误,这可能意味着您的 Python 安装存在问题或缺少了某些核心组件。对于不熟悉SD内部工作原理的用户来说,这无疑增加了解决问题的难度。(简称SD)这一强大技术的旅程中,我们有时可能会遇到一些始料未及的问题。其中,启动一键安装包时遭遇的“Python 无法找到模块‘urlib’”的报错,就是许多新手用户可能会碰到的一个挑战。在使用图生图功能时遇到错误提示,显示为“'Image'对象不支持下标操作”。

【随想录】Day34—第八章 贪心算法 part03

每到一个站点后,此时是有补充有消耗的,关注点:当前还剩余多少油。

influx 操作_Influxdb简单实用操作-程序员宅基地

文章浏览阅读650次。新的infludb版本已经取消了页面的访问方式,只能使用客户端来查看数据一、influxdb与传统数据库的比较库、表等比较:influxDB传统数据库中的概念database数据库measurement数据库中的表points表里面的一行数据influxdb数据的构成:Point由时间戳(time)、数据(field)、标签(tags)组成。Point属性传统数据库中的概念time每个数据记录时间...

增加PyQt5界面的交通流量预测(模型为CNN_GRU,CNN_BiGRU_ATTENTION,LSTM,Python代码)

对代码和数据集压缩包,感兴趣的可以关注最后一行。3.增加 PyQt5界面效果。2.三个模型和数据集的介绍。展示不同算法的对比指标。

推荐文章

热门文章

相关标签