1# @ohos.application.BackupExtensionAbility (BackupExtensionAbility)
2
3The **BackupExtensionAbility** module provides extended backup and restore capabilities for applications.
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> - The APIs of this module can be used only in the stage model.
10
11## Modules to Import
12
13```ts
14import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
15```
16
17## BundleVersion
18
19Defines the version information required for data restore. You can determine the application data to be restored based on the version information.
20
21**System capability**: SystemCapability.FileManagement.StorageService.Backup
22
23| Name| Type  | Mandatory| Description            |
24| ---- | ------ | ---- | ---------------- |
25| code | number | Yes  | Internal version number of the application.  |
26| name | string | Yes  | Version name of the application.|
27
28## BackupExtensionAbility
29
30Implements backup and restore for application access data. You can use [onBackup](#onbackup) and [onRestore](#onrestore) to implement custom backup and restore operations.
31
32### Properties
33
34**System capability**: SystemCapability.FileManagement.StorageService.Backup
35
36| Name                 | Type                                                             | Mandatory| Description                                               |
37| --------------------- | ----------------------------------------------------------------- | ---- | --------------------------------------------------- |
38| context<sup>11+</sup> | [BackupExtensionContext](js-apis-file-backupextensioncontext.md) | Yes | Context of the BackupExtensionAbility. This context is inherited from [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md).|
39
40### onBackup
41
42onBackup(): void;
43
44Called when data is being backed up. You need to implement extended data backup operations.
45
46**System capability**: SystemCapability.FileManagement.StorageService.Backup
47
48**Example**
49
50  ```ts
51  class BackupExt extends BackupExtensionAbility {
52    async onBackup() {
53      console.log('onBackup');
54    }
55  }
56  ```
57
58### onBackupEx<sup>12+</sup>
59
60onBackupEx(backupInfo: string): string | Promise&lt;string&gt;
61
62Called to pass parameters to the application during the application backup or restore process.
63
64**onBackupEx()** and **onBackup()** are mutually exclusive. If **onBackupEx()** needs to be overridden, call **onBackupEx()** preferentially.
65
66The return value of **onBackupEx()** cannot be an empty string. If an empty string is returned, **onRestore** will be called.
67
68**System capability**: SystemCapability.FileManagement.StorageService.Backup
69
70**Parameters**
71
72| Name          | Type                           | Mandatory| Description                         |
73|---------------| ------------------------------- | ---- |-----------------------------|
74| backupInfo    |string | Yes  | Package information to be passed by the third-party application.|
75
76> **NOTE**
77>
78> The following shows the sample code for synchronous implementation.
79
80**Example**
81
82  ```ts
83  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
84
85  interface ErrorInfo {
86    type: string,
87    errorCode: number,
88    errorInfo: string
89  }
90
91  class BackupExt extends BackupExtensionAbility {
92    onBackupEx(backupInfo: string): string {
93      console.log(`onBackupEx ok`);
94      let errorInfo: ErrorInfo = {
95        type: "ErrorInfo",
96        errorCode: 0,
97        errorInfo: "app customized error info"
98      }
99      return JSON.stringify(errorInfo);
100    }
101  }
102  ```
103
104> **NOTE**
105>
106> The following shows the sample code for asynchronous implementation.
107
108**Example**
109
110  ```ts
111  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
112
113  interface ErrorInfo {
114    type: string,
115    errorCode: number,
116    errorInfo: string
117  }
118
119  class BackupExt extends BackupExtensionAbility {
120    // Asynchronous implementation.
121    async onBackupEx(backupInfo: string): Promise<string> {
122      console.log(`onBackupEx ok`);
123      let errorInfo: ErrorInfo = {
124        type: "ErrorInfo",
125        errorCode: 0,
126        errorInfo: "app customized error info"
127      }
128      return JSON.stringify(errorInfo);
129    }
130  }
131  ```
132
133### onRestore
134
135onRestore(bundleVersion: BundleVersion): void;
136
137Called when data is being restored. You need to implement extended data restore operations.
138
139**System capability**: SystemCapability.FileManagement.StorageService.Backup
140
141**Parameters**
142
143| Name       | Type                           | Mandatory| Description                          |
144| ------------- | ------------------------------- | ---- | ------------------------------ |
145| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
146
147**Example**
148
149  ```ts
150  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
151
152  class BackupExt extends BackupExtensionAbility {
153    async onRestore(bundleVersion : BundleVersion) {
154      console.log(`onRestore ok ${JSON.stringify(bundleVersion)}`);
155    }
156  }
157  ```
158
159### onRestoreEx<sup>12+</sup>
160
161onRestoreEx(bundleVersion: BundleVersion, restoreInfo: string): string | Promise&lt;string&gt;
162
163Called when data is being restored. You need to implement the extended data restore operation. Asynchronous implementation is supported.
164
165**onRestoreEx** and **onRestore** are mutually exclusive. Call **onRestoreEx** preferentially if it is overridden.
166The return value of **onRestoreEx** cannot be an empty string. If an empty string is returned, the system will attempt to call **onRestore**.
167
168The return value of **onRestoreEx()** is in JSON format. For details, see the sample code.
169
170**System capability**: SystemCapability.FileManagement.StorageService.Backup
171
172**Parameters**
173
174| Name       | Type                           | Mandatory| Description                          |
175| ------------- | ------------------------------- | ---- | ------------------------------ |
176| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
177| restoreInfo |string | Yes  | Parameter to be passed in the restore process. This field is reserved.|
178
179> **NOTE**
180>
181> The following shows the sample code for asynchronous implementation.
182
183**Example**
184
185  ```ts
186  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
187  interface ErrorInfo {
188    type: string,
189    errorCode: number,
190    errorInfo: string
191  }
192
193  class BackupExt extends BackupExtensionAbility {
194    // Asynchronous implementation
195    async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> {
196      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
197      let errorInfo: ErrorInfo = {
198        type: "ErrorInfo",
199        errorCode: 0,
200        errorInfo: "app customized error info"
201      }
202      return JSON.stringify(errorInfo);
203    }
204  }
205  ```
206
207> **NOTE**
208>
209> The following shows the sample code for synchronous implementation.
210
211**Example**
212
213```ts
214  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
215  interface ErrorInfo {
216    type: string,
217    errorCode: number,
218    errorInfo: string
219  }
220
221  class BackupExt extends BackupExtensionAbility {
222    // Synchronous implementation
223    onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): string {
224      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
225      let errorInfo: ErrorInfo = {
226        type: "ErrorInfo",
227        errorCode: 0,
228        errorInfo: "app customized error info"
229      }
230      return JSON.stringify(errorInfo);
231    }
232  }
233```
234
235### onProcess<sup>12+</sup>
236
237onProcess(): string;
238
239Called to report the progress information. This callback is executed synchronously and implemented during the execution of **onBackup/onBackupEx** or **onRestore/onRestoreEx**.
240This callback returns the service processing progress of the application. The return value is in JSON format. For details, see the sample code.
241
242**System capability**: SystemCapability.FileManagement.StorageService.Backup
243
244> **NOTE**
245>
246> - The system provides the default processing mechanism if **onProcess** is not implemented. If **onProcess** is used, the return value must strictly comply with that in the sample code.
247> - If **onProcess** is used, **onBackup/onBackupEx** and **onRestore/onRestoreEx** must be asynchronously executed in a dedicated thread. Otherwise, **onProcess** cannot run properly. For details, see the sample code.
248>
249> - The following example shows the recommended use of **onProcess**.
250
251**Example**
252
253  ```ts
254  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
255  import { taskpool } from '@kit.ArkTS';
256
257  interface ProgressInfo {
258    name: string, // appName
259    processed: number, // Processed data records.
260    total: number, // Total count.
261    isPercentage: boolean // (Optional) The value true means to display the progress in percentage; the value false or not implemented means to display the progress by the number of items.
262  }
263
264  class BackupExt extends BackupExtensionAbility {
265    // In the following code, the appJob method is the simulated service code, and args specifies the parameters of appJob(). This method is used to start a worker thread in the task pool.
266    async onBackup() {
267      console.log(`onBackup begin`);
268      let args = 100; // args is a parameter of appJob().
269      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, args);
270      try {
271        await taskpool.execute(jobTask, taskpool.Priority.LOW);
272      } catch (error) {
273        console.error("onBackup error." + error.message);
274      }
275      taskpool.terminateTask (jobTask); // Manually destroy the task.
276      console.log(`onBackup end`);
277    }
278
279    async onRestore() {
280      console.log(`onRestore begin`);
281      let args = 100; // args is a parameter of appJob().
282      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, args);
283      try {
284        await taskpool.execute(jobTask, taskpool.Priority.LOW);
285      } catch (error) {
286        console.error("onRestore error." + error.message);
287      }
288      taskpool.terminateTask (jobTask); // Manually destroy the task.
289      console.log(`onRestore end`);
290    }
291
292
293    onProcess(): string {
294      console.log(`onProcess begin`);
295      let process: string = `{
296       "progressInfo":[
297         {
298          "name": "callact", // appName
299          "processed": 100, // Processed data records.
300          "total": 1000, // Total count.
301          "isPercentage", true // (Optional) The value true means to display the progress in percentage; the value false or not implemented means to display the progress by the number of items.
302         }
303       ]
304      }`;
305      console.log(`onProcess end`);
306      return JSON.stringify(process);
307    }
308  }
309
310  @Concurrent
311  function appJob(args: number) : string {
312    // Service logic.
313    console.log(`appJob begin, args is: ` + args);
314    return "ok";
315  }
316  ```
317