• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.<br>
63**onBackupEx()** and **onBackup()** are mutually exclusive. If **onBackupEx()** needs to be overridden, call **onBackupEx()** preferentially.<br>
64The return value of **onBackupEx()** cannot be an empty string. If an empty string is returned, **onRestore** will be called.
65
66**System capability**: SystemCapability.FileManagement.StorageService.Backup
67
68**Parameters**
69
70| Name          | Type                           | Mandatory| Description                         |
71|---------------| ------------------------------- | ---- |-----------------------------|
72| backupInfo    |string | Yes  | Package information to be passed by the third-party application.|
73
74> **NOTE**
75>
76> The following shows the sample code for synchronous implementation.
77
78**Example**
79
80  ```ts
81  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
82
83  interface ErrorInfo {
84    type: string,
85    errorCode: number,
86    errorInfo: string
87  }
88
89  class BackupExt extends BackupExtensionAbility {
90    onBackupEx(backupInfo: string): string {
91      console.log(`onBackupEx ok`);
92      let errorInfo: ErrorInfo = {
93        type: "ErrorInfo",
94        errorCode: 0,
95        errorInfo: "app customized error info"
96      }
97      return JSON.stringify(errorInfo);
98    }
99  }
100  ```
101
102> **NOTE**
103>
104> The following shows the sample code for asynchronous implementation.
105
106**Example**
107
108  ```ts
109  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
110
111  interface ErrorInfo {
112    type: string,
113    errorCode: number,
114    errorInfo: string
115  }
116
117  class BackupExt extends BackupExtensionAbility {
118    // Asynchronous implementation.
119    async onBackupEx(backupInfo: string): Promise<string> {
120      console.log(`onBackupEx ok`);
121      let errorInfo: ErrorInfo = {
122        type: "ErrorInfo",
123        errorCode: 0,
124        errorInfo: "app customized error info"
125      }
126      return JSON.stringify(errorInfo);
127    }
128  }
129  ```
130
131### onRestore
132
133onRestore(bundleVersion: BundleVersion): void;
134
135Called when data is being restored. You need to implement the extended data restore operation.
136
137**System capability**: SystemCapability.FileManagement.StorageService.Backup
138
139**Parameters**
140
141| Name       | Type                           | Mandatory| Description                          |
142| ------------- | ------------------------------- | ---- | ------------------------------ |
143| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
144
145**Example**
146
147  ```ts
148  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
149
150  class BackupExt extends BackupExtensionAbility {
151    async onRestore(bundleVersion : BundleVersion) {
152      console.log(`onRestore ok ${JSON.stringify(bundleVersion)}`);
153    }
154  }
155  ```
156
157### onRestoreEx<sup>12+</sup>
158
159onRestoreEx(bundleVersion: BundleVersion, restoreInfo: string): string | Promise&lt;string&gt;
160
161Called when data is being restored. You need to implement the extended data restore operation. Asynchronous implementation is supported.<br>
162**onRestoreEx** and **onRestore** are mutually exclusive. Call **onRestoreEx** preferentially if it is overridden.<br>
163The return value of **onRestoreEx** cannot be an empty string. If an empty string is returned, the system will attempt to call **onRestore**.<br>
164The return value of **onRestoreEx()** is in JSON format. For details, see the sample code.
165
166**System capability**: SystemCapability.FileManagement.StorageService.Backup
167
168**Parameters**
169
170| Name       | Type                           | Mandatory| Description                          |
171| ------------- | ------------------------------- | ---- | ------------------------------ |
172| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
173| restoreInfo |string | Yes  | Parameter to be passed in the restore process. This field is reserved.|
174
175> **NOTE**
176>
177> The following shows the sample code for asynchronous implementation.
178
179**Example**
180
181  ```ts
182  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
183  interface ErrorInfo {
184    type: string,
185    errorCode: number,
186    errorInfo: string
187  }
188
189  class BackupExt extends BackupExtensionAbility {
190    // Asynchronous implementation
191    async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> {
192      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
193      let errorInfo: ErrorInfo = {
194        type: "ErrorInfo",
195        errorCode: 0,
196        errorInfo: "app customized error info"
197      }
198      return JSON.stringify(errorInfo);
199    }
200  }
201  ```
202
203> **NOTE**
204>
205> The following shows the sample code for synchronous implementation.
206
207**Example**
208
209```ts
210  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
211  interface ErrorInfo {
212    type: string,
213    errorCode: number,
214    errorInfo: string
215  }
216
217  class BackupExt extends BackupExtensionAbility {
218    // Synchronous implementation
219    onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): string {
220      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
221      let errorInfo: ErrorInfo = {
222        type: "ErrorInfo",
223        errorCode: 0,
224        errorInfo: "app customized error info"
225      }
226      return JSON.stringify(errorInfo);
227    }
228  }
229  ```
230
231### onProcess<sup>12+</sup>
232
233onProcess(): string;
234
235Called to return the progress information. This callback is executed synchronously and implemented during the execution of **onBackup/onBackupEx** or **onRestore/onRestoreEx**. This callback returns the service processing progress of the application. The return value is in JSON format. For details, see the sample code.
236
237**System capability**: SystemCapability.FileManagement.StorageService.Backup
238
239> **NOTE**
240> - 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.
241> - 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.
242> - The following example shows the recommended use of **onProcess**.
243
244**Example**
245
246  ```ts
247  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
248  import { taskpool } from '@kit.ArkTS';
249
250  interface ProgressInfo {
251    name: string, // appName
252    processed: number, // Processed data records.
253    total: number, // Total count.
254    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.
255  }
256
257  class BackupExt extends BackupExtensionAbility {
258    // 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.
259    async onBackup() {
260      console.log(`onBackup begin`);
261      let args = 100; // args is a parameter of appJob().
262      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, args);
263      try {
264        await taskpool.execute(jobTask, taskpool.Priority.LOW);
265      } catch (error) {
266        console.error("onBackup error." + error.message);
267      }
268      taskpool.terminateTask (jobTask); // Manually destroy the task.
269      console.log(`onBackup end`);
270    }
271
272    async onRestore() {
273      console.log(`onRestore begin`);
274      let args = 100; // args is a parameter of appJob().
275      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, args);
276      try {
277        await taskpool.execute(jobTask, taskpool.Priority.LOW);
278      } catch (error) {
279        console.error("onRestore error." + error.message);
280      }
281      taskpool.terminateTask (jobTask); // Manually destroy the task.
282      console.log(`onRestore end`);
283    }
284
285
286    onProcess(): string {
287      console.log(`onProcess begin`);
288      let process: string = `{
289       "progressInfo":[
290         {
291          "name": "callact", // appName
292          "processed": 100, // Processed data records.
293          "total": 1000, // Total count.
294          "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.
295         }
296       ]
297      }`;
298      console.log(`onProcess end`);
299      return JSON.stringify(process);
300    }
301  }
302
303  @Concurrent
304  function appJob(args: number) : string {
305    // Service logic.
306    console.log(`appJob begin, args is: ` + args);
307    return "ok";
308  }
309  ```
310