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:
- Use
appRecoveryAPI to configure app restart behavior. - Manually implement cache/data cleanup with the
fsmodule if you need a completion timing. - Trigger
appRecovery.restartApp()only after your cleanup logic completes, instead of relying onclearUpApplicationData.
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
clearUpApplicationDataexits the app immediately and you require a custom solution that ensures restart. - Suitable for HarmonyOS applications that must ensure recovery/restart flow after cleanup.
Top comments (0)