• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.application.BackupExtensionAbility (BackupExtensionAbility)
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @lvzhenjie-->
5<!--Designer: @wang_zhangjun; @chenxi0605-->
6<!--Tester: @liuhonggang123-->
7<!--Adviser: @foryourself-->
8
9The **BackupExtensionAbility** module provides extended backup and restore capabilities for applications.
10
11> **NOTE**
12>
13> - 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.
14>
15> - The APIs of this module can be used only in the stage model.
16
17## Modules to Import
18
19```ts
20import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
21```
22
23## BundleVersion
24
25Defines the version information required for data restore. You can determine the application data to be restored based on the version information.
26
27**System capability**: SystemCapability.FileManagement.StorageService.Backup
28
29| Name| Type  | Mandatory| Description            |
30| ---- | ------ | ---- | ---------------- |
31| code | number | Yes  | Internal version number of the application.  |
32| name | string | Yes  | Version name of the application.|
33
34## BackupExtensionAbility
35
36Implements backup and restore for application access data. You can use [onBackup](#onbackup) and [onRestore](#onrestore) to implement custom backup and restore operations.
37
38### Properties
39
40**System capability**: SystemCapability.FileManagement.StorageService.Backup
41
42| Name                 | Type                                                             | Mandatory| Description                                               |
43| --------------------- | ----------------------------------------------------------------- | ---- | --------------------------------------------------- |
44| 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).|
45
46### onBackup
47
48onBackup(): void
49
50Called when data is being backed up. You need to implement extended data backup operations.
51
52**System capability**: SystemCapability.FileManagement.StorageService.Backup
53
54**Example**
55
56  ```ts
57  class BackupExt extends BackupExtensionAbility {
58    async onBackup() {
59      console.log('onBackup');
60    }
61  }
62  ```
63
64### onBackupEx<sup>12+</sup>
65
66onBackupEx(backupInfo: string): string | Promise&lt;string&gt;
67
68Called to pass parameters to the application during the application backup or restore process. It uses a promise to return the result.<br>
69**onBackupEx** and **onBackup** are mutually exclusive. Call **onBackupEx** preferentially if it is overridden.<br>
70The return value of **onBackupEx** cannot be an empty string. If an empty string is returned, **onBackup** will be called.
71
72**System capability**: SystemCapability.FileManagement.StorageService.Backup
73
74**Parameters**
75
76| Name          | Type                           | Mandatory| Description                         |
77|---------------| ------------------------------- | ---- |-----------------------------|
78| backupInfo    |string | Yes  | Package information to be passed by the third-party application.<br>When it is an empty string, you need to determine how to handle this scenario.|
79
80**Return value**
81
82| Type                           | Description   |
83| ----------------------------- | :---- |
84|string \| Promise&lt;string&gt; |Information about the custom backup operation executed by the application, including the backup result and error information. The return value is in JSON format.<br>A promise object is returned for asynchronous operations.<br>A string is returned for synchronous operations.|
85
86> **NOTE**
87>
88> The following shows the sample code for synchronous implementation.
89
90**Example**
91
92```ts
93import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
94
95interface ErrorInfo {
96  type: string,
97  errorCode: number,
98  errorInfo: string
99}
100class BackupExt extends BackupExtensionAbility {
101  onBackupEx(backupInfo: string): string {
102    try {
103      if (backupInfo == "") {
104        // When backupInfo is empty, you need to handle this based on the service logic of the application.
105        console.info("backupInfo is empty");
106      }
107      console.log(`onBackupEx ok`);
108      let errorInfo: ErrorInfo = {
109        type: "ErrorInfo",
110        errorCode: 0,
111        errorInfo: "app customized error info"
112      }
113      return JSON.stringify(errorInfo);
114    } catch (err) {
115      console.error(`BackupExt error. Code:${err.code}, message:${err.message}`);
116    }
117    return "";
118  }
119}
120```
121
122> **NOTE**
123>
124> The following shows the sample code for asynchronous implementation.
125
126**Example**
127
128```ts
129import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
130
131interface ErrorInfo {
132  type: string,
133  errorCode: number,
134  errorInfo: string
135}
136class BackupExt extends BackupExtensionAbility {
137  // Asynchronous implementation.
138  async onBackupEx(backupInfo: string): Promise<string> {
139    try {
140      if (backupInfo == "") {
141        // When backupInfo is empty, you need to handle this based on the service logic of the application.
142        console.info("backupInfo is empty");
143      }
144      console.log(`onBackupEx ok`);
145      let errorInfo: ErrorInfo = {
146        type: "ErrorInfo",
147        errorCode: 0,
148        errorInfo: "app customized error info"
149      }
150      return JSON.stringify(errorInfo);
151    } catch (err) {
152      console.error(`BackupExt error. Code:${err.code}, message:${err.message}`);
153    }
154    return "";
155  }
156}
157```
158
159### onRestore
160
161onRestore(bundleVersion: BundleVersion): void
162
163Called when data is being restored. You need to implement the extended data restore operation.
164
165**System capability**: SystemCapability.FileManagement.StorageService.Backup
166
167**Parameters**
168
169| Name       | Type                           | Mandatory| Description                          |
170| ------------- | ------------------------------- | ---- | ------------------------------ |
171| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
172
173**Example**
174
175  ```ts
176  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
177
178  class BackupExt extends BackupExtensionAbility {
179    async onRestore(bundleVersion : BundleVersion) {
180      console.log(`onRestore ok ${JSON.stringify(bundleVersion)}`);
181    }
182  }
183  ```
184
185### onRestoreEx<sup>12+</sup>
186
187onRestoreEx(bundleVersion: BundleVersion, restoreInfo: string): string | Promise&lt;string&gt;
188
189Called when data is being restored. You need to implement the extended data restore operation. It uses a promise to return the result.<br>
190**onRestoreEx** and **onRestore** are mutually exclusive. Call **onRestoreEx** preferentially if it is overridden.<br>
191The return value of **onRestoreEx** cannot be an empty string. If an empty string is returned, the system will attempt to call **onRestore**.<br>
192The return value of **onRestoreEx** is in JSON format. For details, see the sample code.
193
194**System capability**: SystemCapability.FileManagement.StorageService.Backup
195
196**Parameters**
197
198| Name       | Type                           | Mandatory| Description                          |
199| ------------- | ------------------------------- | ---- | ------------------------------ |
200| bundleVersion | [BundleVersion](#bundleversion) | Yes  | Version information of the application data to be restored.|
201| restoreInfo |string | Yes  | Parameter to be passed in the restore process. This field is reserved.<br>It may be an empty string in some cases.|
202
203**Return value**
204
205| Type                           | Description   |
206| ----------------------------- | :---- |
207| string \| Promise&lt;string&gt; |Information about the custom restore operation executed by the application, including the restore result and error information. The return value is in JSON format.<br>A promise object is returned for asynchronous operations.<br>A string is returned for synchronous operations.|
208
209> **NOTE**
210>
211> The following shows the sample code for asynchronous implementation.
212
213**Example**
214
215```ts
216import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
217interface ErrorInfo {
218  type: string,
219  errorCode: number,
220  errorInfo: string
221}
222class BackupExt extends BackupExtensionAbility {
223  // Asynchronous implementation
224  async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> {
225    try {
226      if (restoreInfo == "") {
227        // When restoreInfo is empty, you need to handle this based on the service logic of the application.
228        console.info("restoreInfo is empty");
229      }
230      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
231      let errorInfo: ErrorInfo = {
232        type: "ErrorInfo",
233        errorCode: 0,
234        errorInfo: "app customized error info"
235      }
236      return JSON.stringify(errorInfo);
237    } catch (err) {
238      console.error(`onRestoreEx error. Code:${err.code}, message:${err.message}`);
239    }
240    return "";
241  }
242}
243```
244
245> **NOTE**
246>
247> The following shows the sample code for synchronous implementation.
248
249**Example**
250
251```ts
252import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
253interface ErrorInfo {
254  type: string,
255  errorCode: number,
256  errorInfo: string
257}
258
259class BackupExt extends BackupExtensionAbility {
260  // Synchronous implementation
261  onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): string {
262    try {
263      if (restoreInfo == "") {
264        // When restoreInfo is empty, you need to handle this based on the service logic of the application.
265        console.info("restoreInfo is empty");
266      }
267      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
268      let errorInfo: ErrorInfo = {
269        type: "ErrorInfo",
270        errorCode: 0,
271        errorInfo: "app customized error info"
272      }
273      return JSON.stringify(errorInfo);
274    } catch (err) {
275      console.error(`onRestoreEx error. Code:${err.code}, message:${err.message}`);
276    }
277    return "";
278  }
279}
280
281```
282
283### onProcess<sup>12+</sup>
284
285onProcess(): string
286
287Called 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.
288
289**System capability**: SystemCapability.FileManagement.StorageService.Backup
290
291**Return value**
292
293| Type                  | Description   |
294| --------------------- | :---- |
295| string |Progress information during the execution of **onBackup** or **onRestore**. The return value is in JSON format.|
296
297> **NOTE**
298>
299> - 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.
300> - 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.
301> - The following example shows the recommended use of **onProcess()**.
302
303**Example**
304
305  ```ts
306  import { BackupExtensionAbility } from '@kit.CoreFileKit';
307  import { taskpool } from '@kit.ArkTS';
308
309  @Sendable
310  class MigrateProgressInfo {
311    private migrateProgress: string = '';
312    private name: string = "test"; // appName
313    private processed: number = 0; // Processed data
314    private total: number = 100; // Total number
315    private isPercentage: boolean = true // (Optional) The value true means to display the progress in percentage; the value false or an unimplemented field means to display the progress by the number of items.
316
317    getMigrateProgress(): string {
318      this.migrateProgress = `{"progressInfo": [{"name": "${this.name}", "processed": "${this.processed}", "total": "${
319        this.total}", "isPercentage": "${this.isPercentage}"}]}`;
320      return this.migrateProgress;
321    }
322
323    updateProcessed(processed: number) {
324      this.processed = processed;
325    }
326  }
327
328  class BackupExt extends BackupExtensionAbility {
329    private progressInfo: MigrateProgressInfo = new MigrateProgressInfo();
330
331    // 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.
332    async onBackup() {
333      console.log(`onBackup begin`);
334      let args = 100; // args is a parameter of appJob().
335      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, this.progressInfo, args);
336      try {
337        await taskpool.execute(jobTask, taskpool.Priority.LOW);
338      } catch (error) {
339        console.error("onBackup error." + error.message);
340      }
341      taskpool.terminateTask(jobTask); // Manually destroy the task.
342      console.log(`onBackup end`);
343    }
344
345    async onRestore() {
346      console.log(`onRestore begin`);
347      let args = 100; // args is a parameter of appJob().
348      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, this.progressInfo, args);
349      try {
350        await taskpool.execute(jobTask, taskpool.Priority.LOW);
351      } catch (error) {
352        console.error("onRestore error." + error.message);
353      }
354      taskpool.terminateTask(jobTask); // Manually destroy the task.
355      console.log(`onRestore end`);
356    }
357
358
359    onProcess(): string {
360      console.log(`onProcess begin`);
361      return this.progressInfo.getMigrateProgress();
362    }
363  }
364
365  @Concurrent
366  function appJob(progressInfo: MigrateProgressInfo, args: number) : string {
367    console.log(`appJob begin, args is: ` + args);
368    // Update the processing progress during service execution.
369    let currentProcessed: number = 0;
370    // Simulate the actual service logic.
371    for (let i = 0; i < args; i++) {
372      currentProcessed = i;
373      progressInfo.updateProcessed(currentProcessed);
374    }
375    return "ok";
376  }
377  ```
378
379### onRelease<sup>20+</sup>
380
381onRelease(scenario: number): Promise&lt;void&gt;
382
383Provides secure exit APIs of the backup and restore framework. It is triggered when the application backup or restore is complete, allowing the application to perform special processing afterward, such as removing temporary files generated during these operations. This API uses a promise to return the result.<br>
384**onRelease** has a timeout mechanism. If the **onRelease** operation is not completed within 5 seconds, the application process exits when the backup and restoration are complete.
385
386**System capability**: SystemCapability.FileManagement.StorageService.Backup
387
388**Parameters**
389
390| Name       | Type                           | Mandatory| Description                          |
391| ------------- | ------------------------------- | ---- | ------------------------------ |
392| scenario | number | Yes  | Indicates the backup or restore scenario.<br>The value **1** indicates the backup scenario.<br>The value **2** indicates the restore scenario.|
393
394**Return value**
395
396| Type                  | Description   |
397| --------------------- | :---- |
398| Promise&lt;void&gt; | Promise that returns no value.|
399
400**Example**
401
402```ts
403// The following describes an example of removing files.
404import { BackupExtensionAbility, fileIo } from '@kit.CoreFileKit';
405
406const SCENARIO_BACKUP: number = 1;
407const SCENARIO_RESTORE: number = 2;
408// Temporary directory to be removed.
409let filePath: string = '/data/storage/el2/base/.temp/';
410
411class BackupExt extends BackupExtensionAbility {
412  async onRelease(scenario: number): Promise<void> {
413    try {
414      if (scenario == SCENARIO_BACKUP) {
415        // In the backup scenario, the application implements the processing. The following describes how to remove temporary files generated during backup.
416        console.info(`onRelease begin`);
417        await fileIo.rmdir(filePath);
418        console.info(`onRelease end, rmdir succeed`);
419      }
420      if (scenario == SCENARIO_RESTORE) {
421        // In the restore scenario, the application implements the processing. The following describes how to remove temporary files generated during restoration.
422        console.info(`onRelease begin`);
423        await fileIo.rmdir(filePath);
424        console.info(`onRelease end, rmdir succeed`);
425      }
426    } catch (error) {
427      console.error(`onRelease failed with error. Code: ${error.code}, message: ${error.message}`);
428    }
429  }
430}
431```
432