How can developers can automatically restart a HarmonyOS app after clearing all app data?

Read the original article:How can developers can automatically restart a HarmonyOS app after clearing all app data?

Question

How can developers automatically restart a HarmonyOS app after clearing all app data, given that ApplicationContext.clearUpApplicationData exits the app without triggering a callback?

Short Answer

ApplicationContext.clearUpApplicationData clears all app data and directly exits the app, so it does not provide a callback for when data is successfully cleared. To achieve the requirement, you need to:

  1. Use appRecovery API to configure app restart behavior.
  2. Manually implement cache/data cleanup with the fs module if you need a completion timing.
  3. Trigger appRecovery.restartApp() only after your cleanup logic completes, instead of relying on clearUpApplicationData.

Solution Code Examples:

1.Configure App Recovery in AbilityStage

   // AbilityStage
   import appRecovery from '@ohos.app.ability.appRecovery';
   import AbilityStage from '@ohos.app.ability.AbilityStage';

   export default class MyAbilityStage extends AbilityStage {
     onCreate() {
       appRecovery.enableAppRecovery(
         appRecovery.RestartFlag.ALWAYS_RESTART,
         appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR,
         appRecovery.SaveModeFlag.SAVE_WITH_FILE
       );

       let want = {
         bundleName: 'com.example.test',
         abilityName: 'EntryAbility'
       }
       appRecovery.setRestartWant(want)
     }
   }

2.Configure Ability as startup

   "module": {
     "name": "entry",
     "srcEntry": "./ets/AbilityStage/AbilityStage.ets",
     ...
   },
   "abilities": [
     {
       "name": "EntryAbility",
       "recoverable": true,
       ...
     }
   ]

3.Restart App on Button Click

   Button('Restart App')
     .onClick(() => {
       appRecovery.restartApp();
     })

4.Manually Clear Cache with fs (timing control)

   import { storageStatistics } from '@kit.CoreFileKit';
   import fs from '@ohos.file.fs';
   import { Context } from '@kit.AbilityKit';
   import { BusinessError } from '@ohos.base';

   @Entry
   @Component
   struct Clearcache {
     build() {
       Button('Clear cache')
         .onClick(() => {
           const context: Context = getContext(this);
           let cacheDir = context.cacheDir;

           fs.listFile(cacheDir).then((filenames) => {
             for (let i = 0; i < filenames.length; i++) {
               let dirPath = cacheDir + filenames[i];
               try {
                 let isDirectory = fs.statSync(dirPath).isDirectory();
                 if (isDirectory) {
                   fs.rmdirSync(dirPath);
                 } else {
                   fs.unlink(dirPath).then(() => {
                     console.info('remove file succeed');
                   }).catch((err: BusinessError) => {
                     console.error("remove file failed: " + err.message);
                   });
                 }
               } catch (e) {
                 console.log(e);
               }
             }
             // ✅ Restart app after cleanup completes
             appRecovery.restartApp();
           })
         })
     }
   }

Applicable Scenarios

  • When you want the application to restart automatically after clearing app cache or local data.
  • When you need precise control of the timing after data deletion (e.g., clear user sessions, local storage, or cache).
  • When clearUpApplicationData exits the app immediately and you require a custom solution that ensures restart.
  • Suitable for HarmonyOS applications that must ensure recovery/restart flow after cleanup.

Reference Link

https://developer.huawei.com/consumer/en/doc/harmonyos-references-V5/js-apis-inner-application-applicationcontext-V5

Written by Mehmet Algul

Leave a Reply