import storageStatistics from "@ohos.file.storageStatistics";
import { common, contextConstant } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
// 获取缓存数据大小
  getCache() {
    storageStatistics.getCurrentBundleStats().then((res)=>{
      let cache =  (res.cacheSize/(1024*1024)).toFixed(2)+'MB'
    })
  }
//   清理缓存
  cleanAppCache(context: Context){
    // el1加密分区
    context.getApplicationContext().area = contextConstant.AreaMode.EL1;
    context.area = contextConstant.AreaMode.EL1;
    const el1AppCacheDir = context.getApplicationContext().cacheDir
    const el1HapCacheDir = context.cacheDir
    // el2加密分区
    context.getApplicationContext().area = contextConstant.AreaMode.EL2;
    context.area = contextConstant.AreaMode.EL2;
    const el2AppCacheDir = context.getApplicationContext().cacheDir
    const el2HapCacheDir = context.cacheDir

    const task = [
      this.clearCacheTask(el1AppCacheDir),
      this.clearCacheTask(el1HapCacheDir),
      this.clearCacheTask(el2AppCacheDir),
      this.clearCacheTask(el2HapCacheDir)
    ]

    Promise.all(task).then(()=>{
      AlertDialog.show({
        title: $r('app.string.tips'),
        message: $r('app.string.clearCacheFinish'),
        alignment: DialogAlignment.Center,
        autoCancel: false,
        primaryButton: {
          value: $r('app.string.confirm'),
          action: () => {
            this.getCache()
          }
        },
      })

    })
  }
clearCacheTask(dir: string): Promise<boolean> {
    return new Promise((resolve) => {
      fileIo.access(dir).then((exist: boolean) => {
        if (exist) {
          fileIo.rmdir(dir)
        }
        resolve(true)
      })
    })
  }
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐