android implements the function of cleaning cache

  • 2021-11-13 18:21:15
  • OfStack

Cleaning cache implementation of android, for your reference, the specific contents are as follows

1. Cleaning the cache starts with figuring out what to clean up

1. The functions of app itself, such as video recording, audio recording and update, will generate files, which need to be cleaned up
2. Default cache address of app cache

2. Find out the folder location to clean up

1. First of all, the function of app depends on where you put it
2. Default cache address: getActivity (). getExternalCacheDir ();
This position is in storage/emulated/0/Android/data/com. xxxxxapp/cache

3. Code function module:

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


/**
 *  Get app Cache size of 
 * 1.  Recorded video /storage/emulated/0/xueliangapp/video/1573972925136.mp4
 * 2.  Recorded audio /storage/emulated/0/xueliangapp/radio/1573972925136.amr
 * 3.  Downloaded update package /storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/files/Download/xueliang_update.apk
 * 4.  Cache /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 Size : "+getDirSize(videoDir));
    radioDir = new File(Environment.getExternalStorageDirectory()+"/xueliangapp/radio");
    Log.d(TAG, "getAppCache: radioDir Size : "+getDirSize(radioDir));
    filesDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    Log.d(TAG, "getAppCache: filesDir Size : "+getDirSize(filesDir));
    ///storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/files, There are download Folder , Inside is the downloaded update package 
    cacheDir = getActivity().getExternalCacheDir();
    Log.d(TAG, "getAppCache: cacheDir Size : "+getDirSize(cacheDir));
    ///storage/emulated/0/Android/data/com.sdxzt.xueliangapp_v3/cache
    fileSize += getDirSize(getActivity().getFilesDir());
    fileSize += getDirSize(getActivity().getCacheDir());// This line is the default cache address , Looking at pictures or something will accumulate cache here 
    fileSize += getDirSize(videoDir);
    fileSize += getDirSize(radioDir);
    fileSize += getDirSize(filesDir);
    fileSize += getDirSize(cacheDir);
    String fileSizeStr = formatFileSize(fileSize);
    Log.d(TAG, "getAppCache:  Total cache size : "+fileSizeStr);
    return fileSizeStr;
  }

  /**
   *  Get the file size ( In bytes )
   * @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();// The length of the file is the size of the file 
      } else if (file.isDirectory()) {
        dirSize += file.length();
        dirSize += getDirSize(file); //  Recursive call to continue statistics 
      }
    }
    return dirSize;
  }

  /**
   *  Format file length 
   * @param fileSize
   * @return
   */
  private String formatFileSize(long fileSize){
    DecimalFormat df = new DecimalFormat("#0.00");// Indicates that at least before the decimal point 1 Bit ,0 Will also display , Keep two digits after 

    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:  Redisplay cache size ");
    Log.d(TAG, "setAppCache:  Current cache "+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:  Cache clearing is complete ");
          ToastUtil.showMsg(getActivity()," Cache clearing is complete ");
        }else {
          ToastUtil.showMsg(getActivity()," Cache cleanup failed ");
          Log.d(TAG, "handlerMessage:  Cache cleanup failed ");
        }
      }
    };

    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();
  }


  /**
   *  Clear the cache directory 
   * @param dir  Directory 
   * @param curTime  Current system time 
   */
  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:  Clear the directory : "+dir.getAbsolutePath());
    return deletedFiles;
 }

Related articles: