Android implements the function of cleaning cache

Android clean cache implementation, for your reference, the specific contents are as follows

1、 To clean up the cache, you should first find out what to clean up

1. The functions of the app itself, such as video recording, recording and updating, will generate files, which need to be cleaned up. 2. The default cache address of the app is cache

2、 Find out the location of the folder to be cleaned

1. First, the function of the app itself depends on where you put it. 2. Default cache address: getactivity(). Getexternalcachedir(); This location is in storage / emulated / 0 / Android / data / com.xxxapp/cache

3、 Code function module:

1. Get the app cache size in bytes. 2. Get the size of a folder in bytes. 3. Convert the byte unit into common units. 4. Set the cache size to the page and clean it up once before and once after. 5. Delete the folder function. 6. Clear the app cache

/**
 * 获取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;
 }

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>