android之清理缓存实现

android之清理缓存实现

一. 清理缓存首先要搞清楚清理哪些东西,

  1. app本身的功能比如录像,录音,更新都会产生文件,需要清理
  2. app的默认缓存地址cache

二. 搞清楚要清理的文件夹位置

  1. 首先app自身的功能就要看自己把它放在了什么位置
  2. 默认缓存地址:getActivity().getExternalCacheDir();
    这个位置是在storage/emulated/0/Android/data/com.xxxxxapp/cache

三. 搞起
代码功能模块:

  1. 获取app缓存大小,以字节为单位
  2. 获取某个文件夹的大小,以字节为单位
  3. 把字节单位换算成常用单位
  4. 把缓存大小设置到页面,清理前一次,清理后一次
  5. 删除文件夹功能
  6. 清除app缓存

    /**
     * 获取app的缓存大小
     * 1. 录制的视频/storage/emulated/0/xueliangapp/video/1573972925136.mp4
     * 2. 录制的音频/storage/emulated/0/xueliangapp/radio/1573972925136.amr
     * 3. 下载的更新包/storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/files/Download/xueliang_update.apk
     * 4. 缓存/storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/cache
     */
    File videoDir,radioDir,filesDir,cacheDir;
    private String  getAppCache(){
        long fileSize = 0;
        String cacheSize = "0KB";
        videoDir  = new File(Environment.getExternalStorageDirectory()+"/xueliangapp/video");
        Log.d(TAG, "getAppCache: videoDir大小: "+getDirSize(videoDir));
        radioDir  = new File(Environment.getExternalStorageDirectory()+"/xueliangapp/radio");
        Log.d(TAG, "getAppCache: radioDir大小: "+getDirSize(radioDir));
        filesDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        Log.d(TAG, "getAppCache: filesDir大小: "+getDirSize(filesDir));
        ///storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/files,这里面有download文件夹,里面是下载的更新包
        cacheDir = getActivity().getExternalCacheDir();
        Log.d(TAG, "getAppCache: cacheDir大小: "+getDirSize(cacheDir));
        ///storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/cache
        fileSize += getDirSize(getActivity().getFilesDir());
        fileSize += getDirSize(getActivity().getCacheDir());//这行是默认的缓存地址,看图片什么的会在这里积累缓存
        fileSize += getDirSize(videoDir);
        fileSize += getDirSize(radioDir);
        fileSize += getDirSize(filesDir);
        fileSize += getDirSize(cacheDir);
        String fileSizeStr = formatFileSize(fileSize);
        Log.d(TAG, "getAppCache: 总缓存大小: "+fileSizeStr);
        return  fileSizeStr;
    }

    /**
     * 获取文件大小(字节为单位)
     * @param dir
     * @return
     */
    private 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 fileSize
     * @return
     */
    private String formatFileSize(long fileSize){
        DecimalFormat df = new DecimalFormat("#0.00");//表示小数点前至少一位,0也会显示,后保留两位

        String fileSizeString = "";
       if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "KB";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }
    private void setAppCache() {
        String fileSize = getAppCache();
        fileSizeTv.setText(fileSize);
        Log.d(TAG, "setAppCache: 重新显示缓存大小");
        Log.d(TAG, "setAppCache: 当前缓存"+fileSize);
    }

    public  void clearAppCache(final Activity activity){

        final Handler handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Log.d(TAG, "handlerMessage: ");
                if (msg.what == 1) {
                    setAppCache();
                    Log.d(TAG, "handlerMessage: 缓存清除完毕");
                    ToastUtil.showMsg(getActivity(),"缓存清除完毕");
                }else {
                    ToastUtil.showMsg(getActivity(),"缓存清除失败");
                    Log.d(TAG, "handlerMessage: 缓存清除失败");
                }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run: ");
                Message msg = new Message();
                try {
                    clearCacheFolder(videoDir,System.currentTimeMillis());
                    clearCacheFolder(radioDir,System.currentTimeMillis());
                    clearCacheFolder(filesDir,System.currentTimeMillis());
                    clearCacheFolder(cacheDir,System.currentTimeMillis());
                    msg.what = 1;
                }catch (Exception e){
                    e.printStackTrace();
                    msg.what = -1;
                }
                handler.sendMessage(msg);
            }
        }).start();
    }


    /**
     * 清除缓存目录
     * @param dir 目录
     * @param curTime 当前系统时间
     */
    private int clearCacheFolder(File dir,long curTime){
        int deletedFiles = 0;
        if (dir!= null && dir.isDirectory()) {
            try {
                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();
            }
        }
        Log.d(TAG, "clearCacheFolder: 清除目录: "+dir.getAbsolutePath());
        return deletedFiles;
  }

你可能感兴趣的:(学习日志)