1# @ohos.app.ability.appRecovery (appRecovery)
2
3The **appRecovery** module provides APIs for recovering faulty applications.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In API version 9, only applications with a single ability in a process can be recovered. In API version 10, applications with multiple abilities in a process can be recovered.
8
9## Modules to Import
10```ts
11import { appRecovery } from '@kit.AbilityKit';
12```
13
14## RestartFlag
15
16Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
17
18**Atomic service API**: This API can be used in atomic services since API version 11.
19
20**System capability**: SystemCapability.Ability.AbilityRuntime.Core
21
22| Name      | Value  | Description      |
23| ---------- | ---- | ---------- |
24| ALWAYS_RESTART   | 0    | The application is restarted in all cases.|
25| RESTART_WHEN_JS_CRASH   | 0x0001    | The application is restarted in the case of JS_CRASH.|
26| RESTART_WHEN_APP_FREEZE   | 0x0002    | The application is restarted in the case of APP_FREEZE.|
27| NO_RESTART           | 0xFFFF    | The application is not restarted in any case.|
28
29## SaveOccasionFlag
30
31Enumerates the scenarios for saving the application state. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
32
33**Atomic service API**: This API can be used in atomic services since API version 11.
34
35**System capability**: SystemCapability.Ability.AbilityRuntime.Core
36
37| Name                         | Value  | Description                                                        |
38| ----------------------------- | ---- | ------------------------------------------------------------ |
39| SAVE_WHEN_ERROR            | 0x0001    | Saving the application state when an application fault occurs.|
40| SAVE_WHEN_BACKGROUND            | 0x0002    | Saving the application state when the application is switched to the background.|
41
42## SaveModeFlag
43
44Enumerates the application state saving modes. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
45
46**Atomic service API**: This API can be used in atomic services since API version 11.
47
48**System capability**: SystemCapability.Ability.AbilityRuntime.Core
49
50| Name                         | Value  | Description                                                        |
51| ----------------------------- | ---- | ------------------------------------------------------------ |
52| SAVE_WITH_FILE             | 0x0001    | The application state is saved and written to the local file cache.|
53| SAVE_WITH_SHARED_MEMORY             | 0x0002    | The application state is saved in the memory. When the application exits due to a fault, it is written to the local file cache.|
54
55## appRecovery.enableAppRecovery
56
57enableAppRecovery(restart?: [RestartFlag](#restartflag), saveOccasion?: [SaveOccasionFlag](#saveoccasionflag), saveMode?: [SaveModeFlag](#savemodeflag)) : void
58
59Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.
60
61**Model restriction**: This API can be used only in the stage model.
62
63**Atomic service API**: This API can be used in atomic services since API version 11.
64
65**System capability**: SystemCapability.Ability.AbilityRuntime.Core
66
67**Parameters**
68
69| Name| Type| Mandatory| Description|
70| -------- | -------- | -------- | -------- |
71| restart | [RestartFlag](#restartflag) | No| Whether the application is restarted upon a fault. By default, the application is restarted.|
72| saveOccasion | [SaveOccasionFlag](#saveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.|
73| saveMode | [SaveModeFlag](#savemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.|
74
75**Example**
76
77```ts
78import { appRecovery, AbilityStage } from '@kit.AbilityKit';
79
80export default class MyAbilityStage extends AbilityStage {
81  onCreate() {
82    appRecovery.enableAppRecovery(
83      appRecovery.RestartFlag.ALWAYS_RESTART,
84      appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR,
85      appRecovery.SaveModeFlag.SAVE_WITH_FILE
86    );
87  }
88}
89```
90
91## appRecovery.restartApp
92
93restartApp(): void
94
95Restarts the current process and starts the first ability that is displayed when the application is started. If the state of this ability is saved, the saved state data is passed into the **wantParam** property in the **want** parameter of the **onCreate** lifecycle callback of the ability.
96
97In API version 10, the ability specified by [setRestartWant](#apprecoverysetrestartwant10) is started. If no ability is specified, the following rules are used:
98- If the ability of the current application running in the foreground supports recovery, that ability is started.
99- If multiple abilities that support recovery is running in the foreground, only the last ability is started.
100- If no ability is running in the foreground, none of them is started.
101
102This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md). The interval between two restarts must be greater than one minute. If this API is called repeatedly within one minute, the application exits but does not restart. The behavior of automatic restart is the same as that of proactive restart.
103
104**Model restriction**: This API can be used only in the stage model.
105
106**Atomic service API**: This API can be used in atomic services since API version 11.
107
108**System capability**: SystemCapability.Ability.AbilityRuntime.Core
109
110
111**Example**
112
113```ts
114import { appRecovery, errorManager } from '@kit.AbilityKit';
115import { BusinessError } from '@kit.BasicServicesKit';
116
117let observer: errorManager.ErrorObserver = {
118  onUnhandledException(errorMsg) {
119    console.log('onUnhandledException, errorMsg: ', errorMsg);
120    appRecovery.restartApp();
121  }
122};
123
124try {
125  errorManager.on('error', observer);
126} catch (paramError) {
127  console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
128}
129```
130
131## appRecovery.saveAppState
132
133saveAppState(): boolean
134
135Saves the application state. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
136
137**Model restriction**: This API can be used only in the stage model.
138
139**Atomic service API**: This API can be used in atomic services since API version 11.
140
141**System capability**: SystemCapability.Ability.AbilityRuntime.Core
142
143**Return value**
144
145| Type| Description|
146| -------- | -------- |
147| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
148
149**Example**
150
151```ts
152import { appRecovery, errorManager } from '@kit.AbilityKit';
153import { BusinessError } from '@kit.BasicServicesKit';
154
155let observer: errorManager.ErrorObserver = {
156  onUnhandledException(errorMsg) {
157    console.log('onUnhandledException, errorMsg: ', errorMsg);
158    appRecovery.saveAppState();
159  }
160};
161
162try {
163  errorManager.on('error', observer);
164} catch (paramError) {
165  console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
166}
167```
168
169## appRecovery.saveAppState<sup>10+</sup>
170
171saveAppState(context?: UIAbilityContext): boolean
172
173Saves the ability state, which will be used for recovery. This API can be used together with the APIs of [errorManager](js-apis-app-ability-errorManager.md).
174
175**Model restriction**: This API can be used only in the stage model.
176
177**Atomic service API**: This API can be used in atomic services since API version 11.
178
179**System capability**: SystemCapability.Ability.AbilityRuntime.Core
180
181**Parameters**
182
183| Name| Type| Mandatory| Description|
184| -------- | -------- | -------- | -------- |
185| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)| No| Context of the target ability.|
186
187**Return value**
188
189| Type| Description|
190| -------- | -------- |
191| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
192
193**Example**
194
195```ts
196import { appRecovery, errorManager } from '@kit.AbilityKit';
197import { BusinessError } from '@kit.BasicServicesKit';
198
199let observer: errorManager.ErrorObserver = {
200  onUnhandledException(errorMsg) {
201    console.log('onUnhandledException, errorMsg: ', errorMsg);
202    appRecovery.saveAppState(this.context);
203  }
204};
205
206try {
207  errorManager.on('error', observer);
208} catch (paramError) {
209  console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
210}
211```
212
213## appRecovery.setRestartWant<sup>10+</sup>
214
215setRestartWant(want: Want): void
216
217Sets an ability that will be recovered. The ability must be a UIAbility in the current bundle.
218
219**Model restriction**: This API can be used only in the stage model.
220
221**Atomic service API**: This API can be used in atomic services since API version 11.
222
223**System capability**: SystemCapability.Ability.AbilityRuntime.Core
224
225**Parameters**
226
227| Name| Type| Mandatory| Description|
228| -------- | -------- | -------- | -------- |
229| want | [Want](js-apis-app-ability-want.md)| Yes| Want of the target ability. You can set the **bundleName** and **abilityName** fields in **Want** to specify the ability.|
230
231**Example**
232
233```ts
234import { appRecovery, Want } from '@kit.AbilityKit';
235
236@Entry
237@Component
238struct Index {
239  build() {
240    Button ("Start to Recover Ability")
241      .fontSize(40)
242      .fontWeight(FontWeight.Bold)
243      .onClick(()=> {
244        // set restart want
245        let want: Want = {
246          bundleName: "ohos.samples.recovery",
247          abilityName: "RecoveryAbility"
248        };
249
250        appRecovery.setRestartWant(want);
251      })
252  }
253}
254```
255