1# @ohos.file.backup (Backup and Restore) (System API) 2 3The **file.backup** module provides APIs for backing up and restoring data 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> - The APIs provided by this module are system APIs. 9 10## Modules to Import 11 12```ts 13import backup from '@ohos.file.backup'; 14``` 15 16## FileMeta 17 18Defines a file metadata object, which includes the application name and file URI. **FileMeta** is an indispensable object for data backup and restore. 19 20**System capability**: SystemCapability.FileManagement.StorageService.Backup 21 22| Name | Type | Mandatory| Description | 23| ---------- | ------ | ---- | --------------------------------------------------------------------------------------------------- | 24| bundleName | string | Yes | Application name, which can be obtained from [bundleManager.BundleInfo](../apis-ability-kit/js-apis-bundleManager-bundleInfo.md).| 25| uri | string | Yes | URI of the file in the application sandbox.<br>Currently, the URI is not in the uniform data format. It can consist of digits (0–9), letters (a–z and A–Z), underscores (_), and period (.) only. | 26 27## FileData 28 29Defines a file data object, which includes the file descriptor (FD) of the file opened. **FileData** is an indispensable object for data backup and restore. 30 31> **NOTE** 32> 33> The **FileData** must be closed after being used. Otherwise, memory leakage may occur. For details about how to close a **FileData** object, see [fs.closeSync](js-apis-file-fs.md#fsclosesync) provided by [@ohos.file.fs](js-apis-file-fs.md). 34 35**System capability**: SystemCapability.FileManagement.StorageService.Backup 36 37| Name| Type | Mandatory| Description | 38| ---- | ------ | ---- | ---------------------------------------- | 39| fd | number | Yes | FD, which can be obtained through the backup service.| 40 41## FileManifestData<sup>12+</sup> 42 43Defines a file data object, which includes the file descriptor (FD) of the file opened. The file opened by **FileManifestData** provides basic information about the files involved in incremental backup or restore. **FileManifestData** is an indispensable object for incremental backup or restore. 44 45> **NOTE** 46> 47> For details about how to close **FileManifestData**, see [fs.closeSync](js-apis-file-fs.md#fsclosesync). 48 49**System capability**: SystemCapability.FileManagement.StorageService.Backup 50 51| Name | Type | Mandatory| Description | 52| ---------- | ------ | ---- | ---------------------------------------- | 53| manifestFd | number | Yes | FD, which can be obtained through the backup service.| 54 55## IncrementalBackupTime<sup>12+</sup> 56 57Represents the time of the last incremental backup. 58 59**System capability**: SystemCapability.FileManagement.StorageService.Backup 60 61| Name | Type | Mandatory| Description | 62| ------------------- | ------ | ---- | --------------------------------------------------------------------------------------------------- | 63| bundleName | string | Yes | Application name, which can be obtained from [bundleManager.BundleInfo](../apis-ability-kit/js-apis-bundleManager-bundleInfo.md).| 64| lastIncrementalTime | number | Yes | Time when the last incremental backup was performed. | 65 66## BackupParams<sup>12+</sup> 67 68Represents optional parameters in JSON strings for backup and restore. 69 70**System capability**: SystemCapability.FileManagement.StorageService.Backup 71 72| Name | Type | Mandatory| Description | 73| ---------- | ------ | ---- | -------------------------------------------------- | 74| parameters | string | No | Optional parameters for backup or restore, in JSON strings. It is empty by default.| 75 76## BackupPriority<sup>12+</sup> 77 78Represents the backup priority. 79 80**System capability**: SystemCapability.FileManagement.StorageService.Backup 81 82| Name | Type | Mandatory| Description | 83| -------- | ------ | ---- | ------------------------------------------------------ | 84| priority | number | No | Backup priority. A larger value indicates a higher priority. If the priorities are the same, the API called first is executed first. The default value is **0**.| 85 86## IncrementalBackupData<sup>12+</sup> 87 88Represents an incremental backup object, which inherits from [IncrementalBackupTime](#incrementalbackuptime12), [FileManifestData](#filemanifestdata12), [BackupParams](#backupparams12), and [BackupPriority](#backuppriority12). 89 90> **NOTE** 91> 92> This object provides information about the last incremental backup time and the FD of the file that contains a list of the files involved in the incremental backup. Optional parameters include backup and restore configuration and backup priority. 93 94**System capability**: SystemCapability.FileManagement.StorageService.Backup 95 96## File 97 98Defines a file object, which 99inherits [FileMeta](#filemeta) and [FileData](#filedata). 100 101> **NOTE** 102> 103> **file.backup.File** is different from [File](js-apis-file-fs.md#file) provided in @ohos.file.fs. The former is an object that inherits from [FileMeta](#filemeta) and [FileData](#filedata), while the latter has only one FD object. Pay attention to the difference between them. 104 105**System capability**: SystemCapability.FileManagement.StorageService.Backup 106 107## File<sup>12+</sup> 108 109Defines a file object, which 110inherits from [FileMeta](#filemeta), [FileData](#filedata), and [FileManifestData](#filemanifestdata12). 111 112> **NOTE** 113> 114> **file.backup.File** is different from [File](js-apis-file-fs.md#file) provided in @ohos.file.fs. The former is an object that inherits from [FileMeta](#filemeta) and [FileData](#filedata), while the latter has only one FD object. Pay attention to the difference between them. 115 116**System capability**: SystemCapability.FileManagement.StorageService.Backup 117 118## GeneralCallbacks 119 120Provides callbacks to be used in the backup or restore process. The backup service uses these callbacks to notify the client of the backup/restore progress of the application. 121 122**System capability**: SystemCapability.FileManagement.StorageService.Backup 123 124### Attributes 125 126**System capability**: SystemCapability.FileManagement.StorageService.Backup 127 128| Name| Type| Read-Only| Optional| Description| 129| -------- | -------- | -------- | -------- | -------- | 130| onBackupSizeReport<sup>18+</sup> | [OnBackupSizeReport](#onbackupsizereport18) | No| Yes| Size of the data to be backed up.| 131 132### onFileReady 133 134onFileReady : AsyncCallback<File> 135 136Called when the file is ready for sending to the client. If the callback is invoked successfully, [File](#file) is returned. Otherwise, an **err** object is returned. 137 138> **NOTE** 139> 140> The **File** returned by **AsyncCallback** is the file.backup.[File](#file). The returned file belongs to the backup service. Once the file is closed, the backup service shall clear the resources used by the file. However, the client must close the file handle first. 141 142**System capability**: SystemCapability.FileManagement.StorageService.Backup 143 144**Error codes** 145 146For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 147 148| ID| Error Message | 149| -------- | ----------------------- | 150| 13600001 | IPC error. | 151| 13900005 | I/O error. | 152| 13900011 | Out of memory. | 153| 13900020 | Invalid argument. | 154| 13900025 | No space left on device. | 155| 13900042 | Unknown error. | 156 157**Example** 158 159 ```ts 160 import fs from '@ohos.file.fs'; 161 import { BusinessError } from '@ohos.base'; 162 163 onFileReady: (err: BusinessError, file: backup.File) => { 164 if (err) { 165 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 166 return; 167 } 168 console.info('onFileReady success with file: ' + file.bundleName + ' ' + file.uri); 169 fs.closeSync(file.fd); 170 } 171 ``` 172 173### onBundleBegin 174 175onBundleBegin : AsyncCallback<string, void | string> 176 177Called when the application backup or restore starts. If the callback is successfully invoked, **bundleName** is returned. Otherwise, an **err** object is returned. Since API version 12, **err** and **bundleName** are returned. 178 179**System capability**: SystemCapability.FileManagement.StorageService.Backup 180 181**Return value** 182 183| Name | Type | Mandatory| Description | 184| ---------- | ------------- | ---- | ----------------------------------------------------------- | 185| bundleName | string | Yes | Application name. | 186| err | BusinessError | No | Error returned if the operation fails. If the operation is successful, **err** is **undefined**, and **data** is the bundle name.| 187 188**Error codes** 189 190For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 191 192| ID| Error Message | 193| -------- | ----------------------------------------------------- | 194| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 195| 13500001 | The application is not added to the backup or restore. | 196| 13500002 | Failed to start application extension Procedure. | 197| 13600001 | IPC error. | 198| 13900005 | I/O error. | 199| 13900011 | Out of memory. | 200| 13900020 | Invalid argument. | 201| 13900025 | No space left on device. | 202| 13900042 | Unknown error. | 203 204**Example** 205 206 ```ts 207 import { BusinessError } from '@ohos.base'; 208 209 onBundleBegin: (err: BusinessError, bundleName: string) => { 210 if (err) { 211 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code)); 212 return; 213 } 214 console.info('onBundleBegin success'); 215 } 216 ``` 217 218 ```ts 219 import { BusinessError } from '@ohos.base'; 220 221 onBundleBegin: (err: BusinessError<string>, bundleName: string) => { 222 if (err) { 223 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 224 return; 225 } 226 console.info('onBundleBegin success'); 227 } 228 ``` 229 230### onBundleEnd 231 232onBundleEnd : AsyncCallback<string, void | string> 233 234Called when the application backup or restore ends. If the callback is successfully invoked, **bundleName** is returned. Otherwise, an **err** object is returned. Since API version 12, **err** and **bundleName** are returned. 235 236**System capability**: SystemCapability.FileManagement.StorageService.Backup 237 238**Return value** 239 240| Name | Type | Mandatory| Description | 241| ---------- | ------------- | ---- | ----------------------------------------------------------- | 242| bundleName | string | Yes | Application name. | 243| err | BusinessError | No | Error returned if the operation fails. If the operation is successful, **err** is **undefined**, and **data** is the bundle name.| 244 245**Error codes** 246 247For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 248 249| ID| Error Message | 250| -------- | ------------------------------- | 251| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 252| 13500003 | Backup or restore timed out. | 253| 13500004 | Application extension death. | 254| 13600001 | IPC error. | 255| 13900005 | I/O error. | 256| 13900011 | Out of memory. | 257| 13900020 | Invalid argument. | 258| 13900025 | No space left on device. | 259| 13900042 | Unknown error. | 260 261**Example** 262 263 ```ts 264 import { BusinessError } from '@ohos.base'; 265 266 onBundleEnd: (err: BusinessError, bundleName: string) => { 267 if (err) { 268 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 269 return; 270 } 271 console.info('onBundleEnd success with bundleName: ' + bundleName); 272 } 273 ``` 274 275 ```ts 276 import { BusinessError } from '@ohos.base'; 277 278 onBundleEnd: (err: BusinessError<string>, bundleName: string) => { 279 if (err) { 280 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 281 return; 282 } 283 console.info('onBundleEnd success'); 284 } 285 ``` 286 287### onAllBundlesEnd 288 289onAllBundlesEnd : AsyncCallback<undefined> 290 291Called when the backup or restore of all applications ends. If the callback fails to be invoked, an **err** object is returned. 292 293**System capability**: SystemCapability.FileManagement.StorageService.Backup 294 295**Error codes** 296 297For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 298 299| ID| Error Message | 300| -------- | ----------------------- | 301| 13600001 | IPC error. | 302| 13900005 | I/O error. | 303| 13900011 | Out of memory. | 304| 13900020 | Invalid argument. | 305| 13900025 | No space left on device. | 306| 13900042 | Unknown error. | 307 308**Example** 309 310 ```ts 311 import { BusinessError } from '@ohos.base'; 312 313 onAllBundlesEnd: (err: BusinessError) => { 314 if (err) { 315 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 316 return; 317 } 318 console.info('onAllBundlesEnd success'); 319 } 320 ``` 321 322### onBackupServiceDied 323 324onBackupServiceDied : Callback<undefined> 325 326Called when the backup service is suspended. If this callback fails to be invoked, an **err** object is returned. 327 328**System capability**: SystemCapability.FileManagement.StorageService.Backup 329 330**Example** 331 332 ```ts 333 onBackupServiceDied: () => { 334 console.info('onBackupServiceDied success'); 335 } 336 ``` 337 338### onResultReport<sup>12+</sup> 339 340onResultReport (bundleName: string, result: string) 341 342Called when the backup or restore is complete. If the callback is invoked successfully, the application bundle name and backup or restore information (such as the number of backed up or restored records or exception information) are returned. 343 344**System capability**: SystemCapability.FileManagement.StorageService.Backup 345 346**Return value** 347 348| Name | Type | Mandatory| Description | 349| ---------- | ------ | ---- | ------------------------------- | 350| bundleName | string | Yes | Bundle name of the application. | 351| result | string | Yes | Application backup/restore information returned in JSON format.| 352 353**Example** 354 355 ```ts 356 import backup from '@ohos.file.backup'; 357 358 onResultReport: (bundleName: string, result: string) => { 359 console.info('onResultReport bundleName : ' + bundleName); 360 console.info('onResultReport result : ' + result); 361 } 362 ``` 363 364### onProcess<sup>12+</sup> 365 366onProcess (bundleName: string, process: string) 367 368Called to report the backup or restore progress information. If the callback is invoked successfully, the progress information or exception information are returned. 369 370**System capability**: SystemCapability.FileManagement.StorageService.Backup 371 372**Return value** 373 374| Name | Type | Mandatory| Description | 375| ---------- | ------ | ---- | ------------------------------- | 376| bundleName | string | Yes | Bundle name of the application. | 377| process | string | Yes | Backup/restore progress information in JSON format.| 378 379**Example** 380 381 ```ts 382 import backup from '@ohos.file.backup'; 383 384 onProcess: (bundleName: string, process: string) => { 385 console.info('onProcess bundleName : ' + bundleName); 386 console.info('onProcess processInfo : ' + process); 387 } 388 ``` 389 390## backup.getBackupVersion<sup>18+</sup> 391 392getBackupVersion(): string; 393 394Obtain the backup or restore version information. 395 396**Required permissions**: ohos.permission.BACKUP 397 398**System capability**: SystemCapability.FileManagement.StorageService.Backup 399 400**Return value** 401 402| Type | Description | 403| ------------------- | ----------------------- | 404| string | Returns the backup or restore version information.<br>The version number is in the API version format. For example, the version number is 16.0 if the internal version is API16.| 405 406**Error codes** 407 408For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 409 410| ID| Error Message | 411| -------- | ----------------------- | 412| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 413| 202 | Permission verification failed, application which is not a system application uses system API. | 414 415**Example** 416 417 ```ts 418 import { BusinessError } from '@ohos.base'; 419 import backup from '@ohos.file.backup'; 420 421 function getBackupVersion() { 422 try { 423 let result = backup.getBackupVersion(); 424 console.info('getBackupVersion success, result: ' + result); 425 } catch (error) { 426 let err: BusinessError = error as BusinessError; 427 console.error('getBackupVersion failed with err: ' + JSON.stringify(err)); 428 } 429 } 430 ``` 431 432**Content example:** 433 434 ```json 435 { "backupVersion" : "16.0" } 436 ``` 437 438## backup.getLocalCapabilities 439 440getLocalCapabilities(callback: AsyncCallback<FileData>): void 441 442Obtains a JSON file that describes local capabilities. This API uses an asynchronous callback to return the result. 443 444**Required permissions**: ohos.permission.BACKUP 445 446**System capability**: SystemCapability.FileManagement.StorageService.Backup 447 448**Parameters** 449 450| Name | Type | Mandatory| Description | 451| -------- | ------------------------------------------ | ---- | -------------------------------------------------- | 452| callback | AsyncCallback<[FileData](#filedata)> | Yes | Callback used to return the **FileData** object obtained.| 453 454**Error codes** 455 456For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 457 458| ID| Error Message | 459| -------- | ----------------------- | 460| 13600001 | IPC error. | 461| 13900005 | I/O error. | 462| 13900011 | Out of memory. | 463| 13900025 | No space left on device. | 464| 13900042 | Unknown error. | 465 466**Example** 467 468 ```ts 469 import fs from '@ohos.file.fs'; 470 import { BusinessError } from '@ohos.base'; 471 472 try { 473 backup.getLocalCapabilities((err: BusinessError, fileData: backup.FileData) => { 474 if (err) { 475 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 476 return; 477 } 478 console.info('getLocalCapabilities success'); 479 console.info('fileData info:' + fileData.fd); 480 fs.closeSync(fileData.fd); 481 }); 482 } catch (error) { 483 let err: BusinessError = error as BusinessError; 484 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 485 } 486 ``` 487 488The capability file can be obtained by using [fs.stat](js-apis-file-fs.md#fsstat-1) of the [@ohos.file.fs](js-apis-file-fs.md) module. The following is an example of the capability file. 489 490 ```json 491 { 492 "backupVersion" : "16.0", 493 "bundleInfos" :[{ 494 "allToBackup" : true, 495 "extensionName" : "BackupExtensionAbility", 496 "name" : "com.example.hiworld", 497 "needToInstall" : false, 498 "spaceOccupied" : 0, 499 "versionCode" : 1000000, 500 "versionName" : "1.0.0" 501 }], 502 "deviceType" : "default", 503 "systemFullName" : "OpenHarmony-4.0.0.0" 504 } 505 ``` 506 507## backup.getLocalCapabilities 508 509getLocalCapabilities(): Promise<FileData> 510 511Obtains a JSON file that describes local capabilities. This API uses a promise to return the result. 512 513**Required permissions**: ohos.permission.BACKUP 514 515**System capability**: SystemCapability.FileManagement.StorageService.Backup 516 517**Return value** 518 519| Type | Description | 520| ------------------------------------ | ------------------------------- | 521| Promise<[FileData](#filedata)> | Promise **FileData** object obtained.| 522 523**Error codes** 524 525For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 526 527| ID| Error Message | 528| -------- | ----------------------- | 529| 13600001 | IPC error. | 530| 13900005 | I/O error. | 531| 13900011 | Out of memory. | 532| 13900025 | No space left on device. | 533| 13900042 | Unknown error. | 534 535**Example** 536 537 ```ts 538 import fs from '@ohos.file.fs'; 539 import { BusinessError } from '@ohos.base'; 540 541 async function getLocalCapabilities() { 542 try { 543 let fileData = await backup.getLocalCapabilities(); 544 console.info('getLocalCapabilities success'); 545 console.info('fileData info:' + fileData.fd); 546 fs.closeSync(fileData.fd); 547 } catch (error) { 548 let err: BusinessError = error as BusinessError; 549 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 550 } 551 } 552 ``` 553 554 The capability file can be obtained by using [fs.stat](js-apis-file-fs.md#fsstat) of the [@ohos.file.fs](js-apis-file-fs.md) module. The following is an example of the capability file. 555 556 ```json 557 { 558 "backupVersion" : "16.0", 559 "bundleInfos" :[{ 560 "allToBackup" : true, 561 "extensionName" : "BackupExtensionAbility", 562 "name" : "com.example.hiworld", 563 "needToInstall" : false, 564 "spaceOccupied" : 0, 565 "versionCode" : 1000000, 566 "versionName" : "1.0.0" 567 }], 568 "deviceType" : "default", 569 "systemFullName" : "OpenHarmony-4.0.0.0" 570 } 571 ``` 572 573## backup.getLocalCapabilities<sup>12+</sup> 574 575getLocalCapabilities(dataList:Array<IncrementalBackupTime>): Promise<FileData> 576 577Obtains local capabilities. The local capabilities of an application are queried based on the **dataList** parameter passed in. This API uses a promise to return the result. 578 579**Required permissions**: ohos.permission.BACKUP 580 581**System capability**: SystemCapability.FileManagement.StorageService.Backup 582 583**Parameters** 584 585| Name | Type | Mandatory| Description | 586| -------- | -------------------------------------------------------------- | ---- | ---------------------------------------------- | 587| dataList | Array<[IncrementalBackupTime](#incrementalbackuptime12)> | Yes | List of the files involved in the incremental backup.| 588 589**Return value** 590 591| Type | Description | 592| ------------------------------------ | ------------------------------- | 593| Promise<[FileData](#filedata)> | Promise **FileData** object obtained.| 594 595**Error codes** 596 597For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 598 599| ID| Error Message | 600| -------- | ---------------------------------------------------------------------------------------------- | 601| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 602| 202 | Permission verification failed, application which is not a system application uses system API. | 603| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 604| 13600001 | IPC error. | 605| 13900005 | I/O error. | 606| 13900011 | Out of memory. | 607| 13900020 | Invalid argument. | 608| 13900025 | No space left on device. | 609| 13900042 | Unknown error. | 610 611**Example** 612 613 ```ts 614 import fs from '@ohos.file.fs'; 615 import { BusinessError } from '@ohos.base'; 616 617 async function getLocalCapabilities() { 618 try { 619 let backupApps: backup.IncrementalBackupTime[] = [{ 620 bundleName: "com.example.hiworld", 621 lastIncrementalTime: 1700107870 // Time of the last incremental backup. 622 }]; 623 let fileData = await backup.getLocalCapabilities(backupApps); 624 console.info('getLocalCapabilities success'); 625 console.info('fileData info:' + fileData.fd); 626 fs.closeSync(fileData.fd); 627 } catch (error) { 628 let err: BusinessError = error as BusinessError; 629 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 630 } 631 } 632 ``` 633 634## backup.getBackupInfo<sup>12+</sup> 635 636getBackupInfo(bundleToBackup: string): string; 637 638Obtains information about the application to back up. 639 640**Required permissions**: ohos.permission.BACKUP 641 642**System capability**: SystemCapability.FileManagement.StorageService.Backup 643 644**Parameters** 645 646| Name | Type | Mandatory| Description | 647| --------------- | -------- | ---- | -------------------------- | 648| bundleToBackup | string | Yes | Name of the application to back up.| 649 650**Return value** 651 652| Type | Description | 653| ------------------- | ----------------------- | 654| string | Application information obtained.| 655 656**Error codes** 657 658For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 659 660| ID| Error Message | 661| -------- | ----------------------- | 662| 13600001 | IPC error. | 663| 13900001 | Operation not permitted. | 664| 13900005 | I/O error. | 665| 13900011 | Out of memory. | 666| 13900020 | Invalid argument. | 667| 13900025 | No space left on device. | 668| 13900042 | Unknown error. | 669 670**Example** 671 672 ```ts 673 import fs from '@ohos.file.fs'; 674 import { BusinessError } from '@ohos.base'; 675 import backup from '@ohos.file.backup'; 676 677 function getBackupInfo() { 678 try { 679 let backupApp = "com.example.hiworld"; 680 let result = backup.getBackupInfo(backupApp); 681 console.info('getBackupInfo success, result: ' + result); 682 } catch (error) { 683 let err: BusinessError = error as BusinessError; 684 console.error('getBackupInfo failed with err: ' + JSON.stringify(err)); 685 } 686 } 687 ``` 688 689## backup.updateTimer<sup>12+</sup> 690 691updateTimer(bundleName: string, timeout: number): void; 692 693Called after **onBundleBegin** and before **onBundleEnd** to set the backup or restore timer. 694 695**Required permissions**: ohos.permission.BACKUP 696 697**System capability**: SystemCapability.FileManagement.StorageService.Backup 698 699**Parameters** 700 701| Name | Type | Mandatory| Description | 702| --------------- | -------- | ---- | -------------------------- | 703| bundleName | string | Yes | Name of the application, for which you want to set the backup or restore duration.| 704| timeout | number | Yes | Maximum backup or restore duration, in ms.<br>Value range: [0, 14400000]| 705 706**Return value** 707 708| Type | Description | 709| ------------------- | ----------------------- | 710| boolean | A Boolean value indicating whether the backup or restore timeout is set successfully. The value **true** indicates that the setting is successful, and the value **false** indicates that the setting fails.| 711 712**Error codes** 713 714| ID| Error Message | 715| -------- | ----------------------- | 716| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 717| 202 | Permission verification failed, application which is not a system application uses system API. | 718| 401 | The input parameter is invalid. | 719 720**Example** 721 722 ```ts 723 import { BusinessError } from '@ohos.base'; 724 import backup from '@ohos.file.backup'; 725 726 function updateTimer() { 727 try { 728 let timeout = 30000; 729 let bundleName = "com.example.hiworld"; 730 let result = backup.updateTimer(bundleName, timeout); 731 if (result) { 732 console.info('updateTimer success'); 733 } else { 734 console.info('updateTimer fail'); 735 } 736 } catch (error) { 737 let err: BusinessError = error as BusinessError; 738 console.error('updateTimer failed with err: ' + JSON.stringify(err)); 739 } 740 } 741 ``` 742 743## backup.updateSendRate<sup>12+</sup> 744 745updateSendRate(bundleName: string, sendRate: number): boolean; 746 747Called after **onBundleBegin** and before **onBundleEnd** to set the backup or restore timer. 748 749**Required permissions**: ohos.permission.BACKUP 750 751**System capability**: SystemCapability.FileManagement.StorageService.Backup 752 753**Parameters** 754 755| Name | Type | Mandatory| Description | 756| --------------- | -------- | ---- | -------------------------- | 757| bundleName|string | Yes | Name of the target application. 758| sendRate | number | Yes | Send rate to set, in file descriptors (FDs) per second.<br>Value range: 0 to 800<br>Default value: 60 FDs/second <br>The value **0** means to stop transmission. If the value is greater than **800**, the send rate is 800 FDs/second.| 759 760**Return value** 761 762| Type | Description | 763| ------------------- | ----------------------- | 764| boolean | A Boolean value indicating whether the send rate is set successfully. The value **true** indicates that the setting is successful, and the value **false** indicates that the setting fails.| 765 766**Error codes** 767 768| ID| Error Message | 769| -------- | ----------------------- | 770| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 771| 202 | Permission verification failed, application which is not a system application uses system API. | 772| 401 | The input parameter is invalid. | 773 774**Example** 775 776 ```ts 777 import { BusinessError } from '@ohos.base'; 778 import backup from '@ohos.file.backup'; 779 780 function updateSendRate() { 781 try { 782 let bundleName = "com.example.myApp"; 783 let sendRate = 300; 784 let result = backup.updateSendRate(bundleName, sendRate); 785 if (result) { 786 console.info('updateSendRate success'); 787 } else { 788 console.info('updateSendRate fail'); 789 } 790 } catch (error) { 791 let err: BusinessError = error as BusinessError; 792 console.error('updateSendRate failed with err: ' + JSON.stringify(err)); 793 } 794 } 795 ``` 796 797## OnBackupSizeReport<sup>18+</sup> 798 799type OnBackupSizeReport = (reportInfo: string) => void; 800 801Called to return the size of the application data to be backed up. 802 803**System capability**: SystemCapability.FileManagement.StorageService.Backup 804 805| Name | Type | Mandatory| Description | 806| -------- | ------------------------------------- | ---- | -------------------- | 807| reportInfo | string | Yes | Called to return the size of the application data to be backed up.| 808 809**Example** 810 811 ```ts 812 import backup from '@ohos.file.backup'; 813 814 onBackupSizeReport: (OnBackupSizeReport) => { 815 console.info('dataSizeCallback success'); 816 console.info('dataSizeCallback report : ' + OnBackupSizeReport); 817 } 818 ``` 819 820## SessionBackup 821 822Provides a backup process object to support the application backup process. Before using the APIs of this class, you need to create a **SessionBackup** instance. 823 824### constructor 825 826constructor(callbacks: GeneralCallbacks); 827 828A constructor used to create a **SessionBackup** instance. 829 830**Required permissions**: ohos.permission.BACKUP 831 832**System capability**: SystemCapability.FileManagement.StorageService.Backup 833 834**Parameters** 835 836| Name | Type | Mandatory| Description | 837| -------- | ------------------------------------- | ---- | -------------------- | 838| callback | [GeneralCallbacks](#generalcallbacks) | Yes | Callbacks to be invoked during the backup process.| 839 840**Example** 841 842 ```ts 843 import fs from '@ohos.file.fs'; 844 import { BusinessError } from '@ohos.base'; 845 846 let generalCallbacks: backup.GeneralCallbacks = { 847 onFileReady: (err: BusinessError, file: backup.File) => { 848 if (err) { 849 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 850 return; 851 } 852 console.info('onFileReady success'); 853 fs.closeSync(file.fd); 854 }, 855 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 856 if (err) { 857 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 858 return; 859 } 860 console.info('onBundleBegin success'); 861 }, 862 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 863 if (err) { 864 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 865 return; 866 } 867 console.info('onBundleEnd success'); 868 }, 869 onAllBundlesEnd: (err: BusinessError) => { 870 if (err) { 871 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 872 return; 873 } 874 console.info('onAllBundlesEnd success'); 875 }, 876 onBackupServiceDied: () => { 877 console.info('service died'); 878 }, 879 onResultReport: (bundleName: string, result: string) => { 880 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 881 }, 882 onProcess: (bundleName: string, process: string) => { 883 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 884 } 885 }; 886 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 887 ``` 888 889### getLocalCapabilities<sup>18+</sup> 890 891getLocalCapabilities(): Promise<FileData> 892 893Obtains a JSON file that describes local capabilities in the backup service. This API uses a promise to return the result. 894 895**Required permissions**: ohos.permission.BACKUP 896 897**System API**: This is a system API. 898 899**System capability**: SystemCapability.FileManagement.StorageService.Backup 900 901**Return value** 902 903| Type | Description | 904| ------------------------------------ | ------------------------------- | 905| Promise<[FileData](#filedata)> | Promise **FileData** object obtained.| 906 907**Error codes** 908 909For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md). 910 911| ID| Error Message | 912| -------- | ------------------------------------------------------------ | 913| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 914| 202 | Permission verification failed, application which is not a system application uses system API. | 915| 13600001 | IPC error. | 916| 13900001 | Operation not permitted. | 917| 13900020 | Invalid argument. | 918| 13900042 | Internal error. | 919 920**Example** 921 922```ts 923 import fs from '@ohos.file.fs'; 924 import { BusinessError } from '@ohos.base'; 925 926 interface test { // Parse the capability file. 927 bundleInfos: []; 928 deviceType: string; 929 systemFullName: string; 930 } 931 932 interface BundleInfo { // Obtain the local capability information of an application. 933 name: string; 934 appIndex: number; 935 versionCode: number; 936 versionName: string; 937 spaceOccupied: number; 938 allToBackup: boolean; 939 increSpaceOccupied?: number; 940 fullBackupOnly: boolean; 941 extensionName: string; 942 restoreDeps: string; 943 supportScene: string; 944 extraInfo: object; 945 } 946 947 let generalCallbacks: backup.GeneralCallbacks = { // Define general callbacks to be used in the backup or restore process. 948 onFileReady: (err: BusinessError, file: backup.File) => { 949 if (err) { 950 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 951 return; 952 } 953 console.info('onFileReady success'); 954 fs.closeSync(file.fd); 955 }, 956 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 957 if (err) { 958 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 959 return; 960 } 961 console.info('onBundleBegin success'); 962 }, 963 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 964 if (err) { 965 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 966 return; 967 } 968 console.info('onBundleEnd success'); 969 }, 970 onAllBundlesEnd: (err: BusinessError) => { 971 if (err) { 972 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 973 return; 974 } 975 console.info('onAllBundlesEnd success'); 976 }, 977 onBackupServiceDied: () => { 978 console.info('service died'); 979 }, 980 onResultReport: (bundleName: string, result: string) => { 981 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 982 }, 983 onProcess: (bundleName: string, process: string) => { 984 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 985 } 986 }; 987 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 988 let basePath = '/data/storage/el2/base/backup'; 989 let path = basePath + '/localCapabilities.json'; // Local path for storing capability files. 990 try { 991 let fileData = await sessionBackup.getLocalCapabilities(); //: obtain the local capability file. 992 if (fileData) { 993 console.info('getLocalCapabilities success'); 994 console.info('fileData info:' + fileData.fd); 995 if (!fs.accessSync(basePath)) { 996 fs.mkdirSync(basePath); 997 console.info('creat success' + basePath); 998 } 999 fs.copyFileSync(fileData.fd, path); // Save the obtained local capability file to the local host. 1000 fs.closeSync(fileData.fd); 1001 } 1002 } catch (error) { 1003 let err: BusinessError = error as BusinessError; 1004 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 1005 } 1006 let data = await fs.readTextSync(path, 'utf8'); // Obtain information from the local capability file. 1007 try { 1008 const jsonsObj: test | null = JSON.parse(data); // Parse the local capability file and print some information. 1009 if (jsonsObj) { 1010 const infos:BundleInfo [] = jsonsObj.bundleInfos; 1011 for (let i = 0; i < infos.length; i++) { 1012 console.info('name: ' + infos[i].name); 1013 console.info('appIndex: ' + infos[i].appIndex); 1014 console.info('allToBackup: ' + infos[i].allToBackup); 1015 } 1016 const systemFullName: string = jsonsObj.systemFullName; 1017 console.info('systemFullName: ' + systemFullName); 1018 const deviceType: string = jsonsObj.deviceType; 1019 console.info('deviceType: ' + deviceType); 1020 } 1021 } catch (error) { 1022 console.error('parse failed with err: ' + JSON.stringify(error)); 1023 } 1024``` 1025 1026The capability file can be obtained by using [fs.stat](js-apis-file-fs.md#fsstat-1) of the [@ohos.file.fs](js-apis-file-fs.md) module. The following is an example of the capability file. 1027 1028 ```json 1029 { 1030 "backupVersion" : "16.0", 1031 "bundleInfos" :[{ 1032 "allToBackup" : true, 1033 "extensionName" : "BackupExtensionAbility", 1034 "name" : "com.example.hiworld", 1035 "needToInstall" : false, 1036 "spaceOccupied" : 0, 1037 "versionCode" : 1000000, 1038 "versionName" : "1.0.0" 1039 }], 1040 "deviceType" : "default", 1041 "systemFullName" : "OpenHarmony-4.0.0.0" 1042 } 1043 ``` 1044 1045### getBackupDataSize<sup>18+</sup> 1046 1047getBackupDataSize(isPreciseScan: boolean, dataList: Array\<IncrementalBackupTime\>): Promise<void> 1048 1049Obtains the amount of data to be backed up. This method is called before **appendBundles**. The scanning result is returned at a fixed interval of 5 seconds by calling the general callback **onBackupSizeReport** asynchronously until all application data in the datalist is returned. 1050 1051**Required permissions**: ohos.permission.BACKUP 1052 1053**System API**: This is a system API. 1054 1055**System capability**: SystemCapability.FileManagement.StorageService.Backup 1056 1057**Parameters** 1058 1059| Name | Type | Mandatory| Description | 1060| ------------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 1061| isPreciseScan | boolean | Yes | Whether to perform accurate scanning. The value **true** means to perform accurate scanning; the value **false** means to perform inaccurate scanning. Inaccurate scanning is fast and is used to estimate the data size. Accurate scanning is slow and returns more accurate result. However, the data to be backed up may change. Therefore, the precise scanning result may not match the actual backup data size.| 1062| dataList | Array<[IncrementalBackupTime](#incrementalbackuptime12)> | Yes | Backup application list, which describes the application whose data size is to be obtained and the last backup time. For a full backup, set this parameter to **0**.| 1063 1064**Error codes** 1065 1066For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md). 1067 1068| ID| Error Message | 1069| -------- | ------------------------------------------------------------ | 1070| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 1071| 202 | Permission verification failed, application which is not a system application uses system API. | 1072| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild. | 1073| 13600001 | IPC error. | 1074| 13900001 | Operation not permitted. | 1075| 13900020 | Invalid argument. | 1076| 13900042 | Internal error. | 1077 1078**Example** 1079 1080```ts 1081 import fs from '@ohos.file.fs'; 1082 import { BusinessError } from '@ohos.base'; 1083 1084 interface scanedInfos { // Parse the scanning result. 1085 scaned: []; 1086 scanning: string; 1087 } 1088 1089 interface ScanedInfo { // Parse the scanning result of an application. 1090 bundleName: string; 1091 dataSize: number; 1092 incDataSize: number; 1093 } 1094 1095 let generalCallbacks: backup.GeneralCallbacks = { // Define general callbacks to be used in the backup or restore process. 1096 onFileReady: (err: BusinessError, file: backup.File) => { 1097 if (err) { 1098 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1099 return; 1100 } 1101 console.info('onFileReady success'); 1102 fs.closeSync(file.fd); 1103 }, 1104 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1105 if (err) { 1106 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1107 return; 1108 } 1109 console.info('onBundleBegin success'); 1110 }, 1111 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1112 if (err) { 1113 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1114 return; 1115 } 1116 console.info('onBundleEnd success'); 1117 }, 1118 onAllBundlesEnd: (err: BusinessError) => { 1119 if (err) { 1120 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1121 return; 1122 } 1123 console.info('onAllBundlesEnd success'); 1124 }, 1125 onBackupServiceDied: () => { 1126 console.info('service died'); 1127 }, 1128 onResultReport: (bundleName: string, result: string) => { 1129 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1130 }, 1131 onProcess: (bundleName: string, process: string) => { 1132 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1133 }, 1134 onBackupSizeReport: (OnBackupSizeReport) => { // The callback function is used together with getBackupDataSize to return the obtained application data size and the bundle name of the application that is obtaining the data size. 1135 console.info('dataSizeCallback success'); 1136 const jsonObj: scanedInfos | null = JSON.parse(OnBackupSizeReport); // Parse and print the returned information. 1137 if (jsonObj) { 1138 const infos: ScanedInfo [] = jsonObj.scaned; 1139 for (let i = 0; i < infos.length; i++) { 1140 console.info('name: ' + infos[i].bundleName); 1141 console.info('dataSize: ' + infos[i].dataSize); 1142 console.info('incDataSize: ' + infos[i].incDataSize); 1143 } 1144 const scanning: string = jsonObj.scanning; 1145 console.info('scanning: ' + scanning); 1146 } 1147 } 1148 }; 1149 1150 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 1151 let backupApps: backup.IncrementalBackupTime[] = [{ 1152 bundleName: "com.example.hiworld", 1153 lastIncrementalTime: 0 // The caller performs incremental backup based on the last recorded time. The value is 0 for full backup. 1154 }]; 1155 try { 1156 sessionBackup.getBackupDataSize(false, backupApps); // Obtain the data to be backed up of a specified application in backupApps. The value false indicates that inaccurate scanning is used. 1157 } catch (error) { 1158 let err: BusinessError = error as BusinessError; 1159 console.error('getBackupDataSize failed with err: ' + JSON.stringify(err)); 1160 } 1161``` 1162 1163**Example of a JSON string returned asynchronously:** 1164 1165```json 1166{ 1167 "scaned" :[ // Scanned application. The result will not be returned in the next callback. 1168 { 1169 "name": "com.example.hiworld", // Application name. 1170 "dataSize": 1006060, // Data size. 1171 "incDataSize":-1 // Incremental data size. The value is -1 for full scan and inaccurate scan, and is the actual incremental data size for incremental accurate scan. 1172 }, 1173 { 1174 "name": "com.example.myAPP", 1175 "dataSize": 5000027, 1176 "incDataSize": -1 1177 } 1178 ], 1179 "scanning" :"com.example.smartAPP" // Application that is being scanned. This field is empty when the last result is returned. 1180} 1181``` 1182 1183### appendBundles 1184 1185appendBundles(bundlesToBackup: string[], callback: AsyncCallback<void>): void 1186 1187Appends the applications whose data needs to be backed up. Currently, the obtained **SessionBackup** instance can be called only once in the entire backup process. This API uses an asynchronous callback to return the result. 1188 1189**Required permissions**: ohos.permission.BACKUP 1190 1191**System capability**: SystemCapability.FileManagement.StorageService.Backup 1192 1193**Parameters** 1194 1195| Name | Type | Mandatory| Description | 1196| --------------- | ------------------------- | ---- | ---------------------------- | 1197| bundlesToBackup | string[] | Yes | Array of the application names to append. | 1198| callback | AsyncCallback<void> | Yes | Callback used to return the result.| 1199 1200**Error codes** 1201 1202For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1203 1204| ID| Error Message | 1205| -------- | ----------------------- | 1206| 13600001 | IPC error | 1207| 13900001 | Operation not permitted | 1208| 13900005 | I/O error | 1209| 13900011 | Out of memory | 1210| 13900020 | Invalid argument | 1211| 13900025 | No space left on device | 1212| 13900042 | Unknown error | 1213 1214**Example** 1215 1216 ```ts 1217 import fs from '@ohos.file.fs'; 1218 import { BusinessError } from '@ohos.base'; 1219 1220 let generalCallbacks: backup.GeneralCallbacks = { 1221 onFileReady: (err: BusinessError, file: backup.File) => { 1222 if (err) { 1223 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1224 return; 1225 } 1226 console.info('onFileReady success'); 1227 fs.closeSync(file.fd); 1228 }, 1229 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1230 if (err) { 1231 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1232 return; 1233 } 1234 console.info('onBundleBegin success'); 1235 }, 1236 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1237 if (err) { 1238 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1239 return; 1240 } 1241 console.info('onBundleEnd success'); 1242 }, 1243 onAllBundlesEnd: (err: BusinessError) => { 1244 if (err) { 1245 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1246 return; 1247 } 1248 console.info('onAllBundlesEnd success'); 1249 }, 1250 onBackupServiceDied: () => { 1251 console.info('service died'); 1252 }, 1253 onResultReport: (bundleName: string, result: string) => { 1254 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1255 }, 1256 onProcess: (bundleName: string, process: string) => { 1257 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1258 } 1259 }; 1260 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 1261 try { 1262 let backupApps: Array<string> = [ 1263 "com.example.hiworld", 1264 ]; 1265 sessionBackup.appendBundles(backupApps, (err: BusinessError) => { 1266 if (err) { 1267 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 1268 return; 1269 } 1270 console.info('appendBundles success'); 1271 }); 1272 } catch (error) { 1273 let err: BusinessError = error as BusinessError; 1274 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 1275 } 1276 ``` 1277 1278### appendBundles 1279 1280appendBundles(bundlesToBackup: string[], infos?: string[]): Promise<void> 1281 1282Appends the applications whose data needs to be backed up. Currently, the obtained **SessionBackup** instance can be called only once in the entire backup process. This API uses a promise to return the result. 1283 1284From API version 12, the optional parameter **infos** is added to carry information about each application to be backed up. The mappings between **infos** and **bundlesToBackup** are identified by index. 1285 1286**Required permissions**: ohos.permission.BACKUP 1287 1288**System capability**: SystemCapability.FileManagement.StorageService.Backup 1289 1290**Parameters** 1291 1292| Name | Type | Mandatory| Description | 1293| --------------- | -------- | ---- | -------------------------- | 1294| bundlesToBackup | string[] | Yes | Array of the application names to append.| 1295| infos | string[] | No | Array of the information about each application to be backed up. The mappings between **infos** and **bundlesToBackup** are identified by index. It is left blank by default. This parameter is supported since API version 12.| 1296 1297**Return value** 1298 1299| Type | Description | 1300| ------------------- | ----------------------- | 1301| Promise<void> | Promise that returns no value.| 1302 1303**Error codes** 1304 1305For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1306 1307| ID| Error Message | 1308| -------- | ----------------------- | 1309| 13600001 | IPC error | 1310| 13900001 | Operation not permitted | 1311| 13900005 | I/O error | 1312| 13900011 | Out of memory | 1313| 13900020 | Invalid argument | 1314| 13900025 | No space left on device | 1315| 13900042 | Unknown error | 1316 1317**Example** 1318 1319 ```ts 1320 import fs from '@ohos.file.fs'; 1321 import { BusinessError } from '@ohos.base'; 1322 1323 let generalCallbacks: backup.GeneralCallbacks = { 1324 onFileReady: (err: BusinessError, file: backup.File) => { 1325 if (err) { 1326 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1327 return; 1328 } 1329 console.info('onFileReady success'); 1330 fs.closeSync(file.fd); 1331 }, 1332 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1333 if (err) { 1334 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1335 return; 1336 } 1337 console.info('onBundleBegin success'); 1338 }, 1339 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1340 if (err) { 1341 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 1342 return; 1343 } 1344 console.info('onBundleEnd success'); 1345 }, 1346 onAllBundlesEnd: (err: BusinessError) => { 1347 if (err) { 1348 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1349 return; 1350 } 1351 console.info('onAllBundlesEnd success'); 1352 }, 1353 onBackupServiceDied: () => { 1354 console.info('service died'); 1355 }, 1356 onResultReport: (bundleName: string, result: string) => { 1357 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1358 }, 1359 onProcess: (bundleName: string, process: string) => { 1360 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1361 } 1362 }; 1363 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 1364 async function appendBundles() { 1365 try { 1366 let backupApps: Array<string> = [ 1367 "com.example.hiworld", 1368 "com.example.myApp" 1369 ]; 1370 await sessionBackup.appendBundles(backupApps); 1371 console.info('appendBundles success'); 1372 // Application information is carried. In the following, infos, details, and type are fixed parameters. 1373 let infos: Array<string> = [ 1374 ` 1375 { 1376 "infos": [ 1377 { 1378 "details": [ 1379 { 1380 "detail": [ 1381 { 1382 "key1": "value1", 1383 "key2": "value2" 1384 } 1385 ] 1386 } 1387 ], 1388 "type": "unicast", 1389 "bundleName": "com.example.hiworld" 1390 } 1391 ] 1392 }, 1393 { 1394 "infos": [ 1395 { 1396 "details": [ 1397 { 1398 "detail": [ 1399 { 1400 "key1": "value1", 1401 "key2": "value2" 1402 } 1403 ] 1404 } 1405 ], 1406 "type": "unicast", 1407 "bundleName": "com.example.myApp" 1408 } 1409 ] 1410 } 1411 ` 1412 ] 1413 await sessionBackup.appendBundles(backupApps, infos); 1414 console.info('appendBundles success'); 1415 } catch (error) { 1416 let err: BusinessError = error as BusinessError; 1417 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 1418 } 1419 } 1420 ``` 1421 1422### release<sup>12+</sup> 1423 1424release(): Promise<void> 1425 1426Releases the backup session when the backup process is complete. This API disconnects the application from the backup and restore service and exits the service. This API uses a promise to return the result. 1427 1428**Required permissions**: ohos.permission.BACKUP 1429 1430**System capability**: SystemCapability.FileManagement.StorageService.Backup 1431 1432**Return value** 1433 1434| Type | Description | 1435| ------------------- | ----------------------- | 1436| Promise<void> | Promise that returns no value.| 1437 1438**Error codes** 1439 1440For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1441 1442| ID| Error Message | 1443| -------- | ---------------------------------------------------------------------------------------------- | 1444| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 1445| 202 | Permission verification failed, application which is not a system application uses system API. | 1446| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 1447| 13600001 | IPC error. | 1448| 13900001 | Operation not permitted. | 1449| 13900005 | I/O error. | 1450| 13900042 | Unknown error. | 1451 1452**Example** 1453 1454 ```ts 1455 import fs from '@ohos.file.fs'; 1456 import { BusinessError } from '@ohos.base'; 1457 1458 let generalCallbacks: backup.GeneralCallbacks = { 1459 onFileReady: (err: BusinessError, file: backup.File) => { 1460 if (err) { 1461 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1462 return; 1463 } 1464 console.info('onFileReady success'); 1465 fs.closeSync(file.fd); 1466 }, 1467 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1468 if (err) { 1469 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1470 return; 1471 } 1472 console.info('onBundleBegin success'); 1473 }, 1474 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1475 if (err) { 1476 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 1477 return; 1478 } 1479 console.info('onBundleEnd success'); 1480 }, 1481 onAllBundlesEnd: (err: BusinessError) => { 1482 if (err) { 1483 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1484 return; 1485 } 1486 console.info('onAllBundlesEnd success'); 1487 }, 1488 onBackupServiceDied: () => { 1489 console.info('service died'); 1490 }, 1491 onResultReport: (bundleName: string, result: string) => { 1492 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1493 }, 1494 onProcess: (bundleName: string, process: string) => { 1495 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1496 } 1497 }; 1498 let sessionBackup = new backup.SessionBackup(generalCallbacks); // Create a backup process. 1499 async function release() { 1500 try { 1501 await sessionBackup.release(); 1502 console.info('release success'); 1503 } catch (error) { 1504 let err: BusinessError = error as BusinessError; 1505 console.error('release failed with err: ' + JSON.stringify(err)); 1506 } 1507 } 1508 ``` 1509 1510### cancel<sup>18+</sup> 1511 1512cancel(bundleName: string): number; 1513 1514Called to cancel the backup of an application when data exceptions occur. 1515 1516**Required permissions**: ohos.permission.BACKUP 1517 1518**System capability**: SystemCapability.FileManagement.StorageService.Backup 1519 1520**Parameters** 1521 1522| Name | Type | Mandatory| Description | 1523| --------------- | -------- | ---- | -------------------------- | 1524| bundleName | string | Yes | Application name.| 1525 1526**Return value** 1527 1528| Type | Description | 1529| ------------------- | ----------------------- | 1530| number | Cancelled.<br>**0**: The task is successfully cancelled.<br> **13500011**: The task to be cancelled is not started.<br> **13500012**: The task to be cancelled does not exist.| 1531 1532**Error codes** 1533 1534For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1535 1536| ID| Error Message | 1537| -------- | ---------------------------------------------------------------------------------------------- | 1538| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 1539| 202 | Permission verification failed, application which is not a system application uses system API. | 1540| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 1541 1542**Example** 1543 1544 ```ts 1545 import fs from '@ohos.file.fs'; 1546 import { BusinessError } from '@ohos.base'; 1547 import backup from '@ohos.file.backup'; 1548 1549 sessionBackup?: backup.SessionBackup; 1550 1551 let generalCallbacks: backup.GeneralCallbacks = { 1552 onFileReady: (err: BusinessError, file: backup.File) => { 1553 if (err) { 1554 // If the FD fails to be passed, call the cancel API to cancel the backup task of the application. 1555 let result = this.sessionBackup.cancel("com.example.myapplication"); 1556 console.info('cancel result:' + result); 1557 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1558 return; 1559 } 1560 console.info('onFileReady success'); 1561 fs.closeSync(file.fd); 1562 }, 1563 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1564 if (err) { 1565 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1566 return; 1567 } 1568 console.info('onBundleBegin success'); 1569 }, 1570 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1571 if (err) { 1572 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 1573 return; 1574 } 1575 console.info('onBundleEnd success'); 1576 }, 1577 onAllBundlesEnd: (err: BusinessError) => { 1578 if (err) { 1579 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1580 return; 1581 } 1582 console.info('onAllBundlesEnd success'); 1583 }, 1584 onBackupServiceDied: () => { 1585 console.info('service died'); 1586 }, 1587 onResultReport: (bundleName: string, result: string) => { 1588 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1589 }, 1590 onProcess: (bundleName: string, process: string) => { 1591 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1592 } 1593 }; 1594 this.sessionBackup = new backup.SessionBackup(generalCallbacks); // Backup creation process. 1595 ``` 1596 1597## SessionRestore 1598 1599Provides an object to support the application restore process. Before using the APIs of this class, you need to create a **SessionRestore** instance. 1600 1601### constructor 1602 1603constructor(callbacks: GeneralCallbacks); 1604 1605A constructor used to create a **SessionRestore** instance. 1606 1607**Required permissions**: ohos.permission.BACKUP 1608 1609**System capability**: SystemCapability.FileManagement.StorageService.Backup 1610 1611**Parameters** 1612 1613| Name | Type | Mandatory| Description | 1614| -------- | ------------------------------------- | ---- | -------------------- | 1615| callback | [GeneralCallbacks](#generalcallbacks) | Yes | Callbacks to be invoked during the data restore process.| 1616 1617**Example** 1618 1619 ```ts 1620 import fs from '@ohos.file.fs'; 1621 import { BusinessError } from '@ohos.base'; 1622 1623 let generalCallbacks: backup.GeneralCallbacks = { 1624 onFileReady: (err: BusinessError, file: backup.File) => { 1625 if (err) { 1626 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1627 return; 1628 } 1629 console.info('onFileReady success'); 1630 fs.closeSync(file.fd); 1631 }, 1632 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1633 if (err) { 1634 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1635 return; 1636 } 1637 console.info('onBundleBegin success'); 1638 }, 1639 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1640 if (err) { 1641 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 1642 return; 1643 } 1644 console.info('onBundleEnd success'); 1645 }, 1646 onAllBundlesEnd: (err: BusinessError) => { 1647 if (err) { 1648 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1649 return; 1650 } 1651 console.info('onAllBundlesEnd success'); 1652 }, 1653 onBackupServiceDied: () => { 1654 console.info('service died'); 1655 }, 1656 onResultReport: (bundleName: string, result: string) => { 1657 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1658 }, 1659 onProcess: (bundleName: string, process: string) => { 1660 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1661 } 1662 }; 1663 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 1664 ``` 1665 1666### getLocalCapabilities<sup>18+</sup> 1667 1668getLocalCapabilities(): Promise<FileData> 1669 1670Called to obtain a JSON file that describes local capabilities during restore service. This API uses a promise to return the result. 1671 1672**Required permissions**: ohos.permission.BACKUP 1673 1674**System API**: This is a system API. 1675 1676**System capability**: SystemCapability.FileManagement.StorageService.Backup 1677 1678**Return value** 1679 1680| Type | Description | 1681| ------------------------------------ | ------------------------------- | 1682| Promise<[FileData](#filedata)> | Promise **FileData** object obtained.| 1683 1684**Error codes** 1685 1686For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md). 1687 1688| ID| Error Message | 1689| -------- | ------------------------------------------------------------ | 1690| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 1691| 202 | Permission verification failed, application which is not a system application uses system API. | 1692| 13600001 | IPC error. | 1693| 13900001 | Operation not permitted. | 1694| 13900020 | Invalid argument. | 1695| 13900042 | Internal error. | 1696 1697**Example** 1698 1699```ts 1700 import fs from '@ohos.file.fs'; 1701 import { BusinessError } from '@ohos.base'; 1702 1703 interface test { // Parse the capability file. 1704 bundleInfos: []; 1705 deviceType: string; 1706 systemFullName: string; 1707 } 1708 1709 interface BundleInfo { // Obtain the local capability information of an application. 1710 name: string; 1711 appIndex: number; 1712 versionCode: number; 1713 versionName: string; 1714 spaceOccupied: number; 1715 allToBackup: boolean; 1716 increSpaceOccupied?: number; 1717 fullBackupOnly: boolean; 1718 extensionName: string; 1719 restoreDeps: string; 1720 supportScene: string; 1721 extraInfo: object; 1722 } 1723 1724 let generalCallbacks: backup.GeneralCallbacks = { // Define general callbacks to be used in the backup or restore process. 1725 onFileReady: (err: BusinessError, file: backup.File) => { 1726 if (err) { 1727 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1728 return; 1729 } 1730 console.info('onFileReady success'); 1731 fs.closeSync(file.fd); 1732 }, 1733 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1734 if (err) { 1735 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1736 return; 1737 } 1738 console.info('onBundleBegin success'); 1739 }, 1740 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1741 if (err) { 1742 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 1743 return; 1744 } 1745 console.info('onBundleEnd success'); 1746 }, 1747 onAllBundlesEnd: (err: BusinessError) => { 1748 if (err) { 1749 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1750 return; 1751 } 1752 console.info('onAllBundlesEnd success'); 1753 }, 1754 onBackupServiceDied: () => { 1755 console.info('service died'); 1756 }, 1757 onResultReport: (bundleName: string, result: string) => { 1758 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1759 }, 1760 onProcess: (bundleName: string, process: string) => { 1761 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1762 } 1763 }; 1764 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 1765 let basePath = '/data/storage/el2/base/backup'; 1766 let path = basePath + '/localCapabilities.json'; // Local path for storing capability files. 1767 try { 1768 let fileData = await sessionRestore.getLocalCapabilities(); //: obtain the local capability file. 1769 if (fileData) { 1770 console.info('getLocalCapabilities success'); 1771 console.info('fileData info:' + fileData.fd); 1772 if (!fs.accessSync(basePath)) { 1773 fs.mkdirSync(basePath); 1774 console.info('creat success' + basePath); 1775 } 1776 fs.copyFileSync(fileData.fd, path); // Save the obtained local capability file to the local host. 1777 fs.closeSync(fileData.fd); 1778 } 1779 } catch (error) { 1780 let err: BusinessError = error as BusinessError; 1781 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 1782 } 1783 let data = await fs.readTextSync(path, 'utf8'); // Obtain information from the local capability file. 1784 try { 1785 const jsonsObj: test | null = JSON.parse(data); // Parse the local capability file and print some information. 1786 if (jsonsObj) { 1787 const infos:BundleInfo [] = jsonsObj.bundleInfos; 1788 for (let i = 0; i < infos.length; i++) { 1789 console.info('name: ' + infos[i].name); 1790 console.info('appIndex: ' + infos[i].appIndex); 1791 console.info('allToBackup: ' + infos[i].allToBackup); 1792 } 1793 const systemFullName: string = jsonsObj.systemFullName; 1794 console.info('systemFullName: ' + systemFullName); 1795 const deviceType: string = jsonsObj.deviceType; 1796 console.info('deviceType: ' + deviceType); 1797 } 1798 } catch (error) { 1799 console.error('parse failed with err: ' + JSON.stringify(error)); 1800 } 1801``` 1802 1803The capability file can be obtained by using [fs.stat](js-apis-file-fs.md#fsstat-1) of the [@ohos.file.fs](js-apis-file-fs.md) module. The following is an example of the capability file. 1804 1805 ```json 1806 { 1807 "backupVersion" : "16.0", 1808 "bundleInfos" :[{ 1809 "allToBackup" : true, 1810 "extensionName" : "BackupExtensionAbility", 1811 "name" : "com.example.hiworld", 1812 "needToInstall" : false, 1813 "spaceOccupied" : 0, 1814 "versionCode" : 1000000, 1815 "versionName" : "1.0.0" 1816 }], 1817 "deviceType" : "default", 1818 "systemFullName" : "OpenHarmony-4.0.0.0" 1819 } 1820 ``` 1821 1822### appendBundles 1823 1824appendBundles(remoteCapabilitiesFd: number, bundlesToBackup: string[], callback: AsyncCallback<void>): void 1825 1826Appends the applications whose data needs to be restored. Currently, the obtained **SessionRestore** instance can be called only once in the entire restore process. This API uses an asynchronous callback to return the result. 1827 1828> **NOTE** 1829> 1830> - During the data restore, the capability file needs to be verified. 1831> - Therefore, **remoteCapabilitiesFd** can be obtained by using the [getLocalCapabilities](#backupgetlocalcapabilities) API provided by the backup service. You can modify the parameters based on the actual situation of your application. You can also use the JSON file example provided by **getLocalCapabilities** to generate a capability file. 1832 1833**Required permissions**: ohos.permission.BACKUP 1834 1835**System capability**: SystemCapability.FileManagement.StorageService.Backup 1836 1837**Parameters** 1838 1839| Name | Type | Mandatory| Description | 1840| -------------------- | ------------------------- | ---- | ---------------------------------- | 1841| remoteCapabilitiesFd | number | Yes | FD of the file containing the capabilities to be restored.| 1842| bundlesToBackup | string[] | Yes | Array of the application names to append. | 1843| callback | AsyncCallback<void> | Yes | Callback used to return the result.| 1844 1845**Error codes** 1846 1847For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1848 1849| ID| Error Message | 1850| -------- | ----------------------- | 1851| 13600001 | IPC error. | 1852| 13900001 | Operation not permitted. | 1853| 13900005 | I/O error. | 1854| 13900011 | Out of memory. | 1855| 13900020 | Invalid argument. | 1856| 13900025 | No space left on device. | 1857| 13900042 | Unknown error. | 1858 1859**Example** 1860 1861 ```ts 1862 import fs from '@ohos.file.fs'; 1863 import { BusinessError } from '@ohos.base'; 1864 1865 let generalCallbacks: backup.GeneralCallbacks = { 1866 onFileReady: (err: BusinessError, file: backup.File) => { 1867 if (err) { 1868 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1869 return; 1870 } 1871 console.info('onFileReady success'); 1872 fs.closeSync(file.fd); 1873 }, 1874 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1875 if (err) { 1876 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1877 return; 1878 } 1879 console.info('onBundleBegin success'); 1880 }, 1881 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 1882 if (err) { 1883 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 1884 return; 1885 } 1886 console.info('onBundleEnd success'); 1887 }, 1888 onAllBundlesEnd: (err: BusinessError) => { 1889 if (err) { 1890 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 1891 return; 1892 } 1893 console.info('onAllBundlesEnd success'); 1894 }, 1895 onBackupServiceDied: () => { 1896 console.info('service died'); 1897 }, 1898 onResultReport: (bundleName: string, result: string) => { 1899 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 1900 }, 1901 onProcess: (bundleName: string, process: string) => { 1902 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 1903 } 1904 }; 1905 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 1906 async function appendBundles() { 1907 let fileData : backup.FileData = { 1908 fd : -1 1909 } 1910 try { 1911 fileData = await backup.getLocalCapabilities(); 1912 console.info('getLocalCapabilities success'); 1913 let restoreApps: Array<string> = [ 1914 "com.example.hiworld", 1915 ]; 1916 sessionRestore.appendBundles(fileData.fd, restoreApps, (err: BusinessError) => { 1917 if (err) { 1918 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 1919 return; 1920 } 1921 console.info('appendBundles success'); 1922 }); 1923 } catch (error) { 1924 let err: BusinessError = error as BusinessError; 1925 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 1926 } finally { 1927 fs.closeSync(fileData.fd); 1928 } 1929 } 1930 ``` 1931 1932### appendBundles 1933 1934appendBundles(remoteCapabilitiesFd: number, bundlesToBackup: string[], infos?: string[]): Promise<void> 1935 1936Appends the applications whose data needs to be restored. From API version 12, the optional parameter **infos** is added to carry information about each application to be restored. The mappings between **infos** and **bundlesToBackup** are identified by index. 1937Currently, the obtained **SessionRestore** instance can be called only once in the entire restore process. This API uses a promise to return the result. 1938 1939> **NOTE** 1940> 1941> - During the data restore, the capability file needs to be verified. 1942> - You can use [getLocalCapabilities](#backupgetlocalcapabilities) to obtain **remoteCapabilitiesFd**, 1943 and modify the parameters based on the application to be restored. You can also use the JSON file example provided by **getLocalCapabilities** to generate a capability file. 1944 1945**Required permissions**: ohos.permission.BACKUP 1946 1947**System capability**: SystemCapability.FileManagement.StorageService.Backup 1948 1949**Parameters** 1950 1951| Name | Type | Mandatory| Description | 1952| -------------------- | -------- | ---- | ---------------------------------- | 1953| remoteCapabilitiesFd | number | Yes | FD of the file containing the capabilities to be restored.| 1954| bundlesToBackup | string[] | Yes | Array of the application names to append. | 1955| infos<sup>12+</sup> | string[] | No | Array of the information about each application to be restored. The mappings between **infos** and **bundlesToBackup** are identified by index. It is left blank by default. This parameter is supported since API version 12.| 1956 1957**Return value** 1958 1959| Type | Description | 1960| ------------------- | ----------------------- | 1961| Promise<void> | Promise that returns no value.| 1962 1963**Error codes** 1964 1965For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 1966 1967| ID| Error Message | 1968| -------- | ----------------------- | 1969| 13600001 | IPC error. | 1970| 13900001 | Operation not permitted. | 1971| 13900005 | I/O error. | 1972| 13900011 | Out of memory. | 1973| 13900020 | Invalid argument. | 1974| 13900025 | No space left on device. | 1975| 13900042 | Unknown error. | 1976 1977**Example** 1978 1979 ```ts 1980 import fs from '@ohos.file.fs'; 1981 import { BusinessError } from '@ohos.base'; 1982 1983 let generalCallbacks: backup.GeneralCallbacks = { 1984 onFileReady: (err: BusinessError, file: backup.File) => { 1985 if (err) { 1986 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 1987 return; 1988 } 1989 console.info('onFileReady success'); 1990 fs.closeSync(file.fd); 1991 }, 1992 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 1993 if (err) { 1994 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 1995 return; 1996 } 1997 console.info('onBundleBegin success'); 1998 }, 1999 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2000 if (err) { 2001 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2002 return; 2003 } 2004 console.info('onBundleEnd success'); 2005 }, 2006 onAllBundlesEnd: (err: BusinessError) => { 2007 if (err) { 2008 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2009 return; 2010 } 2011 console.info('onAllBundlesEnd success'); 2012 }, 2013 onBackupServiceDied: () => { 2014 console.info('service died'); 2015 }, 2016 onResultReport: (bundleName: string, result: string) => { 2017 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2018 }, 2019 onProcess: (bundleName: string, process: string) => { 2020 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2021 } 2022 }; 2023 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2024 async function appendBundles() { 2025 let fileData : backup.FileData = { 2026 fd : -1 2027 } 2028 try { 2029 fileData = await backup.getLocalCapabilities(); 2030 console.info('getLocalCapabilities success'); 2031 let restoreApps: Array<string> = [ 2032 "com.example.hiworld", 2033 ]; 2034 await sessionRestore.appendBundles(fileData.fd, restoreApps); 2035 console.info('appendBundles success'); 2036 // Information of the applications to restore. 2037 let infos: Array<string> = [ 2038 ` 2039 { 2040 "infos":[ 2041 { 2042 "details": [ 2043 { 2044 "detail": [ 2045 { 2046 "source": "com.example.hiworld", // Old bundle name of the application. 2047 "target": "com.example.helloworld" // New bundle name of the application. 2048 } 2049 ], 2050 "type": "app_mapping_relation" 2051 } 2052 ], 2053 "type":"broadcast" 2054 } 2055 ] 2056 } 2057 ` 2058 ] 2059 await sessionRestore.appendBundles(fileData.fd, restoreApps, infos); 2060 console.info('appendBundles success'); 2061 } catch (error) { 2062 let err: BusinessError = error as BusinessError; 2063 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 2064 } finally { 2065 fs.closeSync(fileData.fd); 2066 } 2067 } 2068 ``` 2069 2070### getFileHandle 2071 2072getFileHandle(fileMeta: FileMeta, callback: AsyncCallback<void>): void 2073 2074Obtains the handle to the shared file from the service. This API uses an asynchronous callback to return the result. 2075 2076> **NOTE** 2077> 2078> - This interface is part of the zero-copy feature, which reduces unnecessary memory copies and increases transmission efficiency. For details about the zero-copy methods, see the zero-copy APIs such as [fs.copyFile](js-apis-file-fs.md#fscopyfile) provided by [@ohos.file.fs](js-apis-file-fs.md). 2079> - Before using **getFileHandle**, you need to obtain a **SessionRestore** instance and add the applications with data to be restored by using **appendBundles**. 2080> - You can use **onFileReady** to obtain the file handle. When file operations are completed at the client, you need to use **publishFile** to publish the file. 2081> - **getFileHandle** can be called multiple times based on the number of files to be restored. 2082> - File to be restored cannot be a relative path (**../**) or soft link. 2083 2084**Required permissions**: ohos.permission.BACKUP 2085 2086**System capability**: SystemCapability.FileManagement.StorageService.Backup 2087 2088**Parameters** 2089 2090| Name | Type | Mandatory| Description | 2091| -------- | ------------------------- | ---- | -------------------------------- | 2092| fileMeta | [FileMeta](#filemeta) | Yes | Metadata of the file to restore. | 2093| callback | AsyncCallback<void> | Yes | Callback used to return the result.| 2094 2095**Error codes** 2096 2097For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2098 2099| ID| Error Message | 2100| -------- | ----------------------- | 2101| 13600001 | IPC error. | 2102| 13900001 | Operation not permitted. | 2103| 13900020 | Invalid argument. | 2104| 13900042 | Unknown error. | 2105 2106**Example** 2107 2108 ```ts 2109 import fs from '@ohos.file.fs'; 2110 import { BusinessError } from '@ohos.base'; 2111 2112 let generalCallbacks: backup.GeneralCallbacks = { 2113 onFileReady: (err: BusinessError, file: backup.File) => { 2114 if (err) { 2115 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2116 return; 2117 } 2118 console.info('onFileReady success'); 2119 fs.closeSync(file.fd); 2120 }, 2121 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2122 if (err) { 2123 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 2124 return; 2125 } 2126 console.info('onBundleBegin success'); 2127 }, 2128 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2129 if (err) { 2130 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2131 return; 2132 } 2133 console.info('onBundleEnd success'); 2134 }, 2135 onAllBundlesEnd: (err: BusinessError) => { 2136 if (err) { 2137 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2138 return; 2139 } 2140 console.info('onAllBundlesEnd success'); 2141 }, 2142 onBackupServiceDied: () => { 2143 console.info('service died'); 2144 }, 2145 onResultReport: (bundleName: string, result: string) => { 2146 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2147 }, 2148 onProcess: (bundleName: string, process: string) => { 2149 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2150 } 2151 }; 2152 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2153 let fileMeta: backup.FileMeta = { 2154 bundleName: "com.example.hiworld", 2155 uri: "test.txt" 2156 } 2157 sessionRestore.getFileHandle(fileMeta, (err: BusinessError) => { 2158 if (err) { 2159 console.error('getFileHandle failed with err: ' + JSON.stringify(err)); 2160 } 2161 console.info('getFileHandle success'); 2162 }); 2163 ``` 2164 2165### getFileHandle 2166 2167getFileHandle(fileMeta: FileMeta): Promise<void> 2168 2169Obtains the handle to the shared file from the service. This API uses a promise to return the result. 2170 2171> **NOTE** 2172> 2173> - This interface is part of the zero-copy feature, which reduces unnecessary memory copies and increases transmission efficiency. For details about the zero-copy methods, see the zero-copy APIs such as [fs.copyFile](js-apis-file-fs.md#fscopyfile) provided by [@ohos.file.fs](js-apis-file-fs.md). 2174> - Before using **getFileHandle**, you need to obtain a **SessionRestore** instance and add the applications with data to be restored by using **appendBundles**. 2175> - You can use **onFileReady** to obtain the file handle. When file operations are completed at the client, you need to use **publishFile** to publish the file. 2176> - **getFileHandle** can be called multiple times based on the number of files to be restored. 2177> - File to be restored cannot be a relative path (**../**) or soft link. 2178 2179**Required permissions**: ohos.permission.BACKUP 2180 2181**System capability**: SystemCapability.FileManagement.StorageService.Backup 2182 2183**Parameters** 2184 2185| Name | Type | Mandatory| Description | 2186| -------- | --------------------- | ---- | ------------------ | 2187| fileMeta | [FileMeta](#filemeta) | Yes | Metadata of the file to restore.| 2188 2189**Return value** 2190 2191| Type | Description | 2192| ------------------- | ----------------------- | 2193| Promise<void> | Promise that returns no value.| 2194 2195**Error codes** 2196 2197For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2198 2199| ID| Error Message | 2200| -------- | ----------------------- | 2201| 13600001 | IPC error. | 2202| 13900001 | Operation not permitted. | 2203| 13900020 | Invalid argument. | 2204| 13900042 | Unknown error. | 2205 2206**Example** 2207 2208 ```ts 2209 import fs from '@ohos.file.fs'; 2210 import { BusinessError } from '@ohos.base'; 2211 2212 let generalCallbacks: backup.GeneralCallbacks = { 2213 onFileReady: (err: BusinessError, file: backup.File) => { 2214 if (err) { 2215 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2216 return; 2217 } 2218 console.info('onFileReady success'); 2219 fs.closeSync(file.fd); 2220 }, 2221 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2222 if (err) { 2223 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 2224 return; 2225 } 2226 console.info('onBundleBegin success'); 2227 }, 2228 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2229 if (err) { 2230 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2231 return; 2232 } 2233 console.info('onBundleEnd success'); 2234 }, 2235 onAllBundlesEnd: (err: BusinessError) => { 2236 if (err) { 2237 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2238 return; 2239 } 2240 console.info('onAllBundlesEnd success'); 2241 }, 2242 onBackupServiceDied: () => { 2243 console.info('service died'); 2244 }, 2245 onResultReport: (bundleName: string, result: string) => { 2246 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2247 }, 2248 onProcess: (bundleName: string, process: string) => { 2249 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2250 } 2251 }; 2252 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2253 async function getFileHandle() { 2254 try { 2255 let fileMeta: backup.FileMeta = { 2256 bundleName: "com.example.hiworld", 2257 uri: "test.txt" 2258 } 2259 await sessionRestore.getFileHandle(fileMeta); 2260 console.info('getFileHandle success'); 2261 } catch (error) { 2262 let err: BusinessError = error as BusinessError; 2263 console.error('getFileHandle failed with err: ' + JSON.stringify(err)); 2264 } 2265 } 2266 ``` 2267 2268### publishFile 2269 2270publishFile(fileMeta: FileMeta, callback: AsyncCallback<void>): void 2271 2272Publishes **FileMeta** to the backup service to indicate that the file content is ready. This API uses an asynchronous callback to return the result. 2273 2274> **NOTE** 2275> 2276> - This interface is part of the zero-copy feature, which reduces unnecessary memory copies and increases transmission efficiency. For details about the zero-copy methods, see the zero-copy APIs such as [fs.copyFile](js-apis-file-fs.md#fscopyfile) provided by [@ohos.file.fs](js-apis-file-fs.md). 2277> - After the server returns a file handle through **onFileReady**, the client can copy data to the file corresponding to the file handle provided by the server through zero-copy operations. 2278> - This API can be called only after the caller has written all the data to be restored. The caller must ensure the consistency and integrity of the data to be written. 2279 2280**Required permissions**: ohos.permission.BACKUP 2281 2282**System capability**: SystemCapability.FileManagement.StorageService.Backup 2283 2284**Parameters** 2285 2286| Name | Type | Mandatory| Description | 2287| -------- | ------------------------- | ---- | ---------------------------- | 2288| fileMeta | [FileMeta](#filemeta) | Yes | Metadata of the file to restore. | 2289| callback | AsyncCallback<void> | Yes | Callback used to return the result.| 2290 2291**Error codes** 2292 2293For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2294 2295| ID| Error Message | 2296| -------- | ----------------------- | 2297| 13600001 | IPC error. | 2298| 13900001 | Operation not permitted. | 2299| 13900020 | Invalid argument. | 2300| 13900042 | Unknown error. | 2301 2302**Example** 2303 2304 ```ts 2305 import fs from '@ohos.file.fs'; 2306 import { BusinessError } from '@ohos.base'; 2307 2308 let g_session: backup.SessionRestore; 2309 let initMap = new Map<string, number>(); 2310 let testFileNum = 123; // Number of files required for the restore. 2311 let testBundleName = 'com.example.myapplication'; // Test bundle name. 2312 initMap.set(testBundleName, testFileNum); 2313 let countMap = new Map<string, number>(); 2314 countMap.set(testBundleName, 0); // Initialize the number of files written. 2315 function createSessionRestore() { 2316 let generalCallbacks: backup.GeneralCallbacks = { 2317 onFileReady: (err: BusinessError, file: backup.File) => { 2318 if (err) { 2319 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2320 return; 2321 } 2322 console.info('onFileReady success'); 2323 fs.closeSync(file.fd); 2324 countMap[file.bundleName]++; // Update the number of files written. 2325 // Called only when the number of files to be restored is the same as the number of files actually written. This ensures data consistency and integrity. 2326 if (countMap[file.bundleName] == initMap[file.bundleName]) { // Trigger publishFile when all the files of each package are received. 2327 let fileMeta: backup.FileMeta = { 2328 bundleName: file.bundleName, 2329 uri: '' 2330 } 2331 g_session.publishFile(fileMeta, (err: BusinessError) => { 2332 if (err) { 2333 console.error('publishFile failed with err: ' + JSON.stringify(err)); 2334 return; 2335 } 2336 console.info('publishFile success'); 2337 }); 2338 } 2339 }, 2340 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2341 if (err) { 2342 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 2343 return; 2344 } 2345 console.info('onBundleBegin success'); 2346 }, 2347 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2348 if (err) { 2349 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2350 return; 2351 } 2352 console.info('onBundleEnd success'); 2353 }, 2354 onAllBundlesEnd: (err: BusinessError) => { 2355 if (err) { 2356 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2357 return; 2358 } 2359 console.info('onAllBundlesEnd success'); 2360 }, 2361 onBackupServiceDied: () => { 2362 console.info('service died'); 2363 }, 2364 onResultReport: (bundleName: string, result: string) => { 2365 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2366 }, 2367 onProcess: (bundleName: string, process: string) => { 2368 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2369 } 2370 }; 2371 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2372 return sessionRestore; 2373 } 2374 g_session = createSessionRestore(); 2375 ``` 2376 2377### publishFile 2378 2379publishFile(fileMeta: FileMeta): Promise<void> 2380 2381Publishes **FileMeta** to the backup service to indicate that the file content is ready. This API uses a promise to return the result. 2382 2383> **NOTE** 2384> 2385> - This interface is part of the zero-copy feature, which reduces unnecessary memory copies and increases transmission efficiency. For details about the zero-copy methods, see the zero-copy APIs such as [fs.copyFile](js-apis-file-fs.md#fscopyfile) provided by [@ohos.file.fs](js-apis-file-fs.md). 2386> - After the server returns a file handle through **onFileReady**, the client can copy data to the file corresponding to the file handle provided by the server through zero-copy operations. 2387> - This API can be called only after the caller has written all the data to be restored. The caller must ensure the consistency and integrity of the data to be written. 2388 2389**Required permissions**: ohos.permission.BACKUP 2390 2391**System capability**: SystemCapability.FileManagement.StorageService.Backup 2392 2393**Parameters** 2394 2395| Name | Type | Mandatory| Description | 2396| -------- | --------------------- | ---- | ---------------- | 2397| fileMeta | [FileMeta](#filemeta) | Yes | Metadata of the file to restore.| 2398 2399**Return value** 2400 2401| Type | Description | 2402| ------------------- | ----------------------- | 2403| Promise<void> | Promise that returns no value.| 2404 2405**Error codes** 2406 2407For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2408 2409| ID| Error Message | 2410| -------- | ----------------------- | 2411| 13600001 | IPC error. | 2412| 13900001 | Operation not permitted. | 2413| 13900020 | Invalid argument. | 2414| 13900042 | Unknown error. | 2415 2416**Example** 2417 2418 ```ts 2419 import fs from '@ohos.file.fs'; 2420 import { BusinessError } from '@ohos.base'; 2421 2422 let g_session: backup.SessionRestore; 2423 let initMap = new Map<string, number>(); 2424 let testFileNum = 123; // Number of files required for the restore. 2425 let testBundleName = 'com.example.myapplication'; // Test bundle name. 2426 initMap.set(testBundleName, testFileNum); 2427 let countMap = new Map<string, number>(); 2428 countMap.set(testBundleName, 0); // Initialize the number of files written. 2429 async function publishFile(file: backup.FileMeta) { 2430 let fileMeta: backup.FileMeta = { 2431 bundleName: file.bundleName, 2432 uri: '' 2433 } 2434 await g_session.publishFile(fileMeta); 2435 } 2436 function createSessionRestore() { 2437 let generalCallbacks: backup.GeneralCallbacks = { 2438 onFileReady: (err: BusinessError, file: backup.File) => { 2439 if (err) { 2440 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2441 return; 2442 } 2443 console.info('onFileReady success'); 2444 fs.closeSync(file.fd); 2445 countMap[file.bundleName]++; // Update the number of files written. 2446 // Called only when the number of files to be restored is the same as the number of files actually written. This ensures data consistency and integrity. 2447 if (countMap[file.bundleName] == initMap[file.bundleName]) { // Trigger publishFile when all the files of each package are received. 2448 publishFile(file); 2449 } 2450 console.info('publishFile success'); 2451 }, 2452 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2453 if (err) { 2454 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 2455 return; 2456 } 2457 console.info('onBundleBegin success'); 2458 }, 2459 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2460 if (err) { 2461 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2462 return; 2463 } 2464 console.info('onBundleEnd success'); 2465 }, 2466 onAllBundlesEnd: (err: BusinessError) => { 2467 if (err) { 2468 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2469 return; 2470 } 2471 console.info('onAllBundlesEnd success'); 2472 }, 2473 onBackupServiceDied: () => { 2474 console.info('service died'); 2475 }, 2476 onResultReport: (bundleName: string, result: string) => { 2477 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2478 }, 2479 onProcess: (bundleName: string, process: string) => { 2480 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2481 } 2482 }; 2483 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2484 return sessionRestore; 2485 } 2486 g_session = createSessionRestore(); 2487 ``` 2488 2489### release<sup>12+</sup> 2490 2491release(): Promise<void> 2492 2493Releases the restore session when the restore process is complete. This API disconnects the application from the backup and restore service and exits the service. This API uses a promise to return the result. 2494 2495**Required permissions**: ohos.permission.BACKUP 2496 2497**System capability**: SystemCapability.FileManagement.StorageService.Backup 2498 2499**Return value** 2500 2501| Type | Description | 2502| ------------------- | ----------------------- | 2503| Promise<void> | Promise that returns no value.| 2504 2505**Error codes** 2506 2507For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2508 2509| ID| Error Message | 2510| -------- | ---------------------------------------------------------------------------------------------- | 2511| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 2512| 202 | Permission verification failed, application which is not a system application uses system API. | 2513| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 2514| 13600001 | IPC error. | 2515| 13900001 | Operation not permitted. | 2516| 13900005 | I/O error. | 2517| 13900042 | Unknown error. | 2518 2519**Example** 2520 2521 ```ts 2522 import fs from '@ohos.file.fs'; 2523 import { BusinessError } from '@ohos.base'; 2524 2525 let g_session: backup.SessionRestore; 2526 let initMap = new Map<string, number>(); 2527 let testFileNum = 123; // Number of files required for the restore. 2528 let testBundleName = 'com.example.myapplication'; // Test bundle name. 2529 initMap.set(testBundleName, testFileNum); 2530 let countMap = new Map<string, number>(); 2531 countMap.set(testBundleName, 0); // Initialize the number of files written. 2532 function createSessionRestore() { 2533 let generalCallbacks: backup.GeneralCallbacks = { 2534 onFileReady: (err: BusinessError, file: backup.File) => { 2535 if (err) { 2536 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2537 return; 2538 } 2539 console.info('onFileReady success'); 2540 fs.closeSync(file.fd); 2541 countMap[file.bundleName]++; // Update the number of files written. 2542 // Called only when the number of files to be restored is the same as the number of files actually written. This ensures data consistency and integrity. 2543 if (countMap[file.bundleName] == initMap[file.bundleName]) { // Trigger publishFile when all the files of each package are received. 2544 let fileMeta: backup.FileMeta = { 2545 bundleName: file.bundleName, 2546 uri: '' 2547 } 2548 g_session.publishFile(fileMeta, (err: BusinessError) => { 2549 if (err) { 2550 console.error('publishFile failed with err: ' + JSON.stringify(err)); 2551 return; 2552 } 2553 console.info('publishFile success'); 2554 }); 2555 } 2556 }, 2557 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2558 if (err) { 2559 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2560 return; 2561 } 2562 console.info('onBundleBegin success'); 2563 }, 2564 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2565 if (err) { 2566 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2567 return; 2568 } 2569 console.info('onBundleEnd success'); 2570 }, 2571 onAllBundlesEnd: (err: BusinessError) => { 2572 if (err) { 2573 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2574 return; 2575 } 2576 console.info('onAllBundlesEnd success'); 2577 }, 2578 onBackupServiceDied: () => { 2579 console.info('service died'); 2580 }, 2581 onResultReport: (bundleName: string, result: string) => { 2582 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2583 }, 2584 onProcess: (bundleName: string, process: string) => { 2585 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2586 } 2587 }; 2588 let sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2589 return sessionRestore; 2590 } 2591 g_session = createSessionRestore(); 2592 g_session.release(); 2593 console.info('release success'); 2594 ``` 2595 2596### cancel<sup>18+</sup> 2597 2598cancel(bundleName: string): number; 2599 2600Called to cancel the restoration of an application when data exceptions occur. 2601 2602**Required permissions**: ohos.permission.BACKUP 2603 2604**System capability**: SystemCapability.FileManagement.StorageService.Backup 2605 2606**Parameters** 2607 2608| Name | Type | Mandatory| Description | 2609| --------------- | -------- | ---- | -------------------------- | 2610| bundleName | string | Yes | Application name.| 2611 2612**Return value** 2613 2614| Type | Description | 2615| ------------------- | ----------------------- | 2616| number | Cancelled.<br>**0**: The task is successfully cancelled.<br> **13500011**: The task to be cancelled is not started.<br> **13500012**: The task to be cancelled does not exist.| 2617 2618**Error codes** 2619 2620For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2621 2622| ID| Error Message | 2623| -------- | ---------------------------------------------------------------------------------------------- | 2624| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 2625| 202 | Permission verification failed, application which is not a system application uses system API. | 2626| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 2627 2628**Example** 2629 2630 ```ts 2631 import fs from '@ohos.file.fs'; 2632 import { BusinessError } from '@ohos.base'; 2633 import backup from '@ohos.file.backup'; 2634 2635 sessionRestore?: backup.SessionRestore; 2636 2637 let generalCallbacks: backup.GeneralCallbacks = { 2638 onFileReady: (err: BusinessError, file: backup.File) => { 2639 if (err) { 2640 // If the FD fails to be passed, call the cancel API to cancel the restoration task of the application. 2641 let result = this.sessionRestore.cancel("com.example.myapplication"); 2642 console.info('cancel result:' + result); 2643 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2644 return; 2645 } 2646 console.info('onFileReady success'); 2647 fs.closeSync(file.fd); 2648 }, 2649 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2650 if (err) { 2651 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 2652 return; 2653 } 2654 console.info('onBundleBegin success'); 2655 }, 2656 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2657 if (err) { 2658 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 2659 return; 2660 } 2661 console.info('onBundleEnd success'); 2662 }, 2663 onAllBundlesEnd: (err: BusinessError) => { 2664 if (err) { 2665 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2666 return; 2667 } 2668 console.info('onAllBundlesEnd success'); 2669 }, 2670 onBackupServiceDied: () => { 2671 console.info('service died'); 2672 }, 2673 onResultReport: (bundleName: string, result: string) => { 2674 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2675 }, 2676 onProcess: (bundleName: string, process: string) => { 2677 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2678 } 2679 }; 2680 this.sessionRestore = new backup.SessionRestore(generalCallbacks); // Create a restore process. 2681 ``` 2682 2683## IncrementalBackupSession<sup>12+</sup> 2684 2685An object used to implement the incremental backup of applications. Before using the APIs of this class, you need to create an **IncrementalBackupSession** instance. 2686 2687### constructor<sup>12+</sup> 2688 2689constructor(callbacks: GeneralCallbacks); 2690 2691A constructor used to create an **IncrementalBackupSession** instance. 2692 2693**Required permissions**: ohos.permission.BACKUP 2694 2695**System capability**: SystemCapability.FileManagement.StorageService.Backup 2696 2697**Parameters** 2698 2699| Name | Type | Mandatory| Description | 2700| -------- | ------------------------------------- | ---- | ------------------------ | 2701| callback | [GeneralCallbacks](#generalcallbacks) | Yes | Callbacks to be invoked during the incremental backup process.| 2702 2703**Error codes** 2704 2705For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 2706 2707| ID| Error Message | 2708| -------- | ---------------------------------------------------------------------------------------------- | 2709| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 2710| 202 | Permission verification failed, application which is not a system application uses system API. | 2711| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 2712 2713**Example** 2714 2715 ```ts 2716 import fs from '@ohos.file.fs'; 2717 import { BusinessError } from '@ohos.base'; 2718 2719 let generalCallbacks: backup.GeneralCallbacks = { 2720 onFileReady: (err: BusinessError, file: backup.File) => { 2721 if (err) { 2722 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2723 return; 2724 } 2725 console.info('onFileReady success'); 2726 fs.closeSync(file.fd); 2727 }, 2728 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2729 if (err) { 2730 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2731 return; 2732 } 2733 console.info('onBundleBegin success'); 2734 }, 2735 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2736 if (err) { 2737 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2738 return; 2739 } 2740 console.info('onBundleEnd success'); 2741 }, 2742 onAllBundlesEnd: (err: BusinessError) => { 2743 if (err) { 2744 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2745 return; 2746 } 2747 console.info('onAllBundlesEnd success'); 2748 }, 2749 onBackupServiceDied: () => { 2750 console.info('service died'); 2751 }, 2752 onResultReport: (bundleName: string, result: string) => { 2753 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2754 }, 2755 onProcess: (bundleName: string, process: string) => { 2756 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2757 } 2758 }; 2759 let incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 2760 ``` 2761 2762### getLocalCapabilities<sup>18+</sup> 2763 2764getLocalCapabilities(): Promise<FileData> 2765 2766Obtains a JSON file that describes local capabilities in the incremental backup service. This API uses a promise to return the result. 2767 2768**Required permissions**: ohos.permission.BACKUP 2769 2770**System API**: This is a system API. 2771 2772**System capability**: SystemCapability.FileManagement.StorageService.Backup 2773 2774**Return value** 2775 2776| Type | Description | 2777| ------------------------------------ | ------------------------------- | 2778| Promise<[FileData](#filedata)> | Promise **FileData** object obtained.| 2779 2780**Error codes** 2781 2782For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md). 2783 2784| ID| Error Message | 2785| -------- | ------------------------------------------------------------ | 2786| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 2787| 202 | Permission verification failed, application which is not a system application uses system API. | 2788| 13600001 | IPC error. | 2789| 13900001 | Operation not permitted. | 2790| 13900020 | Invalid argument. | 2791| 13900042 | Internal error. | 2792 2793**Example** 2794 2795```ts 2796 import fs from '@ohos.file.fs'; 2797 import { BusinessError } from '@ohos.base'; 2798 2799 interface test { // Parse the capability file. 2800 bundleInfos: []; 2801 deviceType: string; 2802 systemFullName: string; 2803 } 2804 2805 interface BundleInfo { // Obtain the local capability information of an application. 2806 name: string; 2807 appIndex: number; 2808 versionCode: number; 2809 versionName: string; 2810 spaceOccupied: number; 2811 allToBackup: boolean; 2812 increSpaceOccupied?: number; 2813 fullBackupOnly: boolean; 2814 extensionName: string; 2815 restoreDeps: string; 2816 supportScene: string; 2817 extraInfo: object; 2818 } 2819 2820 let generalCallbacks: backup.GeneralCallbacks = { // Define general callbacks to be used in the backup or restore process. 2821 onFileReady: (err: BusinessError, file: backup.File) => { 2822 if (err) { 2823 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2824 return; 2825 } 2826 console.info('onFileReady success'); 2827 fs.closeSync(file.fd); 2828 }, 2829 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2830 if (err) { 2831 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2832 return; 2833 } 2834 console.info('onBundleBegin success'); 2835 }, 2836 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2837 if (err) { 2838 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2839 return; 2840 } 2841 console.info('onBundleEnd success'); 2842 }, 2843 onAllBundlesEnd: (err: BusinessError) => { 2844 if (err) { 2845 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2846 return; 2847 } 2848 console.info('onAllBundlesEnd success'); 2849 }, 2850 onBackupServiceDied: () => { 2851 console.info('service died'); 2852 }, 2853 onResultReport: (bundleName: string, result: string) => { 2854 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 2855 }, 2856 onProcess: (bundleName: string, process: string) => { 2857 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 2858 } 2859 }; 2860 let incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 2861 let basePath = '/data/storage/el2/base/backup'; 2862 let path = basePath + '/localCapabilities.json'; // Local path for storing capability files. 2863 try { 2864 let fileData = await incrementalBackupSession.getLocalCapabilities(); // Obtain the local capability file. 2865 if (fileData) { 2866 console.info('getLocalCapabilities success'); 2867 console.info('fileData info:' + fileData.fd); 2868 if (!fs.accessSync(basePath)) { 2869 fs.mkdirSync(basePath); 2870 console.info('creat success' + basePath); 2871 } 2872 fs.copyFileSync(fileData.fd, path); // Save the obtained local capability file to the local host. 2873 fs.closeSync(fileData.fd); 2874 } 2875 } catch (error) { 2876 let err: BusinessError = error as BusinessError; 2877 console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); 2878 } 2879 let data = await fs.readTextSync(path, 'utf8'); // Obtain information from the local capability file. 2880 try { 2881 const jsonsObj: test | null = JSON.parse(data); // Parse the local capability file and print some information. 2882 if (jsonsObj) { 2883 const infos:BundleInfo [] = jsonsObj.bundleInfos; 2884 for (let i = 0; i < infos.length; i++) { 2885 console.info('name: ' + infos[i].name); 2886 console.info('appIndex: ' + infos[i].appIndex); 2887 console.info('allToBackup: ' + infos[i].allToBackup); 2888 } 2889 const systemFullName: string = jsonsObj.systemFullName; 2890 console.info('systemFullName: ' + systemFullName); 2891 const deviceType: string = jsonsObj.deviceType; 2892 console.info('deviceType: ' + deviceType); 2893 } 2894 } catch (error) { 2895 console.error('parse failed with err: ' + JSON.stringify(error)); 2896 } 2897``` 2898 2899The capability file can be obtained by using [fs.stat](js-apis-file-fs.md#fsstat-1) of the [@ohos.file.fs](js-apis-file-fs.md) module. The following is an example of the capability file. 2900 2901 ```json 2902 { 2903 "backupVersion" : "16.0", 2904 "bundleInfos" :[{ 2905 "allToBackup" : true, 2906 "extensionName" : "BackupExtensionAbility", 2907 "name" : "com.example.hiworld", 2908 "needToInstall" : false, 2909 "spaceOccupied" : 0, 2910 "versionCode" : 1000000, 2911 "versionName" : "1.0.0" 2912 }], 2913 "deviceType" : "default", 2914 "systemFullName" : "OpenHarmony-4.0.0.0" 2915 } 2916 ``` 2917 2918### getBackupDataSize<sup>18+</sup> 2919 2920getBackupDataSize(isPreciseScan: boolean, dataList: Array\<IncrementalBackupTime\>): Promise<void> 2921 2922Obtains the amount of data to be backed up. This method is called before **appendBundles**. The scanning result is returned at a fixed interval of 5 seconds by calling the general callback **onBackupSizeReport** asynchronously until all application data in the datalist is returned. 2923 2924**Required permissions**: ohos.permission.BACKUP 2925 2926**System API**: This is a system API. 2927 2928**System capability**: SystemCapability.FileManagement.StorageService.Backup 2929 2930**Parameters** 2931 2932| Name | Type | Mandatory| Description | 2933| ------------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 2934| isPreciseScan | boolean | Yes | Whether to perform accurate scanning. Inaccurate scanning is fast and is used to estimate the data size. Accurate scanning is slow and returns more accurate result. However, the data to be backed up may change. Therefore, the precise scanning result may not match the actual backup data size.| 2935| dataList | Array<[IncrementalBackupTime](#incrementalbackuptime12)> | Yes | Backup application list, which describes the application whose data size is to be obtained and the last backup time. For a full backup, set this parameter to **0**.| 2936 2937**Error codes** 2938 2939For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md). 2940 2941| ID| Error Message | 2942| -------- | ------------------------------------------------------------ | 2943| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 2944| 202 | Permission verification failed, application which is not a system application uses system API. | 2945| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild. | 2946| 13600001 | IPC error. | 2947| 13900001 | Operation not permitted. | 2948| 13900020 | Invalid argument. | 2949| 13900042 | Internal error. | 2950 2951**Example** 2952 2953```ts 2954 import fs from '@ohos.file.fs'; 2955 import { BusinessError } from '@ohos.base'; 2956 2957 interface scanedInfos { // Parse the scanning result. 2958 scaned: []; 2959 scanning: string; 2960 } 2961 2962 interface ScanedInfo { // Parse the scanning result of an application. 2963 bundleName: string; 2964 dataSize: number; 2965 incDataSize: number; 2966 } 2967 2968 let generalCallbacks: backup.GeneralCallbacks = { 2969 onFileReady: (err: BusinessError, file: backup.File) => { // Define the universal callbacks to be used in the backup or restore process. 2970 if (err) { 2971 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 2972 return; 2973 } 2974 console.info('onFileReady success'); 2975 fs.closeSync(file.fd); 2976 }, 2977 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 2978 if (err) { 2979 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2980 return; 2981 } 2982 console.info('onBundleBegin success'); 2983 }, 2984 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 2985 if (err) { 2986 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 2987 return; 2988 } 2989 console.info('onBundleEnd success'); 2990 }, 2991 onAllBundlesEnd: (err: BusinessError) => { 2992 if (err) { 2993 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 2994 return; 2995 } 2996 console.info('onAllBundlesEnd success'); 2997 }, 2998 onBackupServiceDied: () => { 2999 console.info('service died'); 3000 }, 3001 onResultReport: (bundleName: string, result: string) => { 3002 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 3003 }, 3004 onProcess: (bundleName: string, process: string) => { 3005 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 3006 }, 3007 onBackupSizeReport: (OnBackupSizeReport) => { // The callback function is used together with getBackupDataSize to return the obtained application data size and the bundle name of the application that is obtaining the data size. 3008 console.info('dataSizeCallback success'); 3009 const jsonObj: scanedInfos | null = JSON.parse(OnBackupSizeReport); // Parse and print the returned information. 3010 if (jsonObj) { 3011 const infos: ScanedInfo [] = jsonObj.scaned; 3012 for (let i = 0; i < infos.length; i++) { 3013 console.info('name: ' + infos[i].bundleName); 3014 console.info('dataSize: ' + infos[i].dataSize); 3015 console.info('incDataSize: ' + infos[i].incDataSize); 3016 } 3017 const scanning: string = jsonObj.scanning; 3018 console.info('scanning: ' + scanning); 3019 } 3020 } 3021 }; 3022 3023 let incrementalBackupSession = new backup.incrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 3024 3025 let backupApps: backup.IncrementalBackupTime[] = [{ 3026 bundleName: "com.example.hiworld", 3027 lastIncrementalTime: 1700107870 // Time of the last incremental backup. 3028 }]; 3029 try { 3030 incrementalBackupSession.getBackupDataSize(true, backupApps); // Obtain the amount of specified application data to be backed up in backupApps. The value true indicates that accurate scanning is used. 3031 } catch (error) { 3032 let err: BusinessError = error as BusinessError; 3033 console.error('getBackupDataSize failed with err: ' + JSON.stringify(err)); 3034 } 3035``` 3036 3037**Example of a JSON string returned asynchronously:** 3038 3039```json 3040{ 3041 "scaned" :[ // Scanned application. The result will not be returned in the next callback. 3042 { 3043 "name": "com.example.hiworld", // Application name. 3044 "dataSize": 1006060, // Data size. 3045 "incDataSize": 50800 // Incremental data size. 3046 }, 3047 { 3048 "name": "com.example.myAPP", 3049 "dataSize": 5000027, 3050 "incDataSize": 232344 3051 } 3052 ], 3053 "scanning" :"com.example.smartAPP" // Application that is being scanned. This field is empty when the last result is returned. 3054} 3055``` 3056 3057### appendBundles<sup>12+</sup> 3058 3059appendBundles(bundlesToBackup: Array<IncrementalBackupData>): Promise<void> 3060 3061Appends applications that require incremental backup. In the current process, **appendBundles** can be called before **Release()** is called. This API uses a promise to return the result. 3062 3063**Required permissions**: ohos.permission.BACKUP 3064 3065**System capability**: SystemCapability.FileManagement.StorageService.Backup 3066 3067**Parameters** 3068 3069| Name | Type | Mandatory| Description | 3070| --------------- | -------------------------------------------------------------- | ---- | -------------------------- | 3071| bundlesToBackup | Array<[IncrementalBackupData](#incrementalbackupdata12)> | Yes | Array of applications that require incremental backup.| 3072 3073**Return value** 3074 3075| Type | Description | 3076| ------------------- | ----------------------- | 3077| Promise<void> | Promise that returns no value.| 3078 3079**Error codes** 3080 3081For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 3082 3083| ID| Error Message | 3084| -------- | ---------------------------------------------------------------------------------------------- | 3085| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 3086| 202 | Permission verification failed, application which is not a system application uses system API. | 3087| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 3088| 13600001 | IPC error. | 3089| 13900001 | Operation not permitted. | 3090| 13900005 | I/O error. | 3091| 13900011 | Out of memory. | 3092| 13900020 | Invalid argument. | 3093| 13900025 | No space left on device. | 3094| 13900042 | Unknown error. | 3095 3096**Example** 3097 3098 ```ts 3099 import fs from '@ohos.file.fs'; 3100 import { BusinessError } from '@ohos.base'; 3101 3102 let generalCallbacks: backup.GeneralCallbacks = { 3103 onFileReady: (err: BusinessError, file: backup.File) => { 3104 if (err) { 3105 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 3106 return; 3107 } 3108 console.info('onFileReady success'); 3109 fs.closeSync(file.fd); 3110 }, 3111 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 3112 if (err) { 3113 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3114 return; 3115 } 3116 console.info('onBundleBegin success'); 3117 }, 3118 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 3119 if (err) { 3120 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3121 return; 3122 } 3123 console.info('onBundleEnd success'); 3124 }, 3125 onAllBundlesEnd: (err: BusinessError) => { 3126 if (err) { 3127 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 3128 return; 3129 } 3130 console.info('onAllBundlesEnd success'); 3131 }, 3132 onBackupServiceDied: () => { 3133 console.info('service died'); 3134 }, 3135 onResultReport: (bundleName: string, result: string) => { 3136 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 3137 }, 3138 onProcess: (bundleName: string, process: string) => { 3139 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 3140 } 3141 }; 3142 let incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 3143 let incrementalBackupData: backup.IncrementalBackupData = { 3144 bundleName: "com.example.hiworld", 3145 lastIncrementalTime: 1700107870, // Timestamp of the last backup. 3146 manifestFd:1 // FD of the manifest file of the last backed. 3147 } 3148 let incrementalBackupDataArray: backup.IncrementalBackupData[] = [incrementalBackupData]; 3149 incrementalBackupSession.appendBundles(incrementalBackupDataArray).then(() => { 3150 console.info('appendBundles success'); 3151 }).catch((err: BusinessError) => { 3152 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 3153 }); // Appends the applications that require incremental backup. 3154 ``` 3155 3156### appendBundles<sup>12+</sup> 3157 3158appendBundles(bundlesToBackup: Array<IncrementalBackupData>, infos: string[]): Promise<void> 3159 3160Appends applications that require incremental backup. In the current process, **appendBundles** can be called before **Release()** is called. This API uses a promise to return the result. 3161 3162**Required permissions**: ohos.permission.BACKUP 3163 3164**System capability**: SystemCapability.FileManagement.StorageService.Backup 3165 3166**Parameters** 3167 3168| Name | Type | Mandatory| Description | 3169| --------------- | -------------------------------------------------------------- | ---- | -------------------------- | 3170| bundlesToBackup | Array<[IncrementalBackupData](#incrementalbackupdata12)> | Yes | Array of applications that require incremental backup.| 3171| infos | string[] | Yes | Array of the information about each application to be backed up. The mappings between **infos** and **bundlesToBackup** are identified by index. This parameter is supported since API version 12.| 3172 3173**Return value** 3174 3175| Type | Description | 3176| ------------------- | ----------------------- | 3177| Promise<void> | Promise that returns no value.| 3178 3179**Error codes** 3180 3181For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 3182 3183| ID| Error Message | 3184| -------- | ---------------------------------------------------------------------------------------------- | 3185| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 3186| 202 | Permission verification failed, application which is not a system application uses system API. | 3187| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 3188| 13600001 | IPC error. | 3189| 13900001 | Operation not permitted. | 3190| 13900005 | I/O error. | 3191| 13900011 | Out of memory. | 3192| 13900020 | Invalid argument. | 3193| 13900025 | No space left on device. | 3194| 13900042 | Unknown error. | 3195 3196**Example** 3197 3198 ```ts 3199 import fs from '@ohos.file.fs'; 3200 import { BusinessError } from '@ohos.base'; 3201 3202 let generalCallbacks: backup.GeneralCallbacks = { 3203 onFileReady: (err: BusinessError, file: backup.File) => { 3204 if (err) { 3205 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 3206 return; 3207 } 3208 console.info('onFileReady success'); 3209 fs.closeSync(file.fd); 3210 }, 3211 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 3212 if (err) { 3213 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3214 return; 3215 } 3216 console.info('onBundleBegin success'); 3217 }, 3218 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 3219 if (err) { 3220 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3221 return; 3222 } 3223 console.info('onBundleEnd success'); 3224 }, 3225 onAllBundlesEnd: (err: BusinessError) => { 3226 if (err) { 3227 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 3228 return; 3229 } 3230 console.info('onAllBundlesEnd success'); 3231 }, 3232 onBackupServiceDied: () => { 3233 console.info('service died'); 3234 }, 3235 onResultReport: (bundleName: string, result: string) => { 3236 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 3237 }, 3238 onProcess: (bundleName: string, process: string) => { 3239 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 3240 } 3241 }; 3242 let incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 3243 let incrementalBackupData: backup.IncrementalBackupData = { 3244 bundleName: "com.example.hiworld", 3245 lastIncrementalTime: 1700107870, // Timestamp of the last backup. 3246 manifestFd:1 // FD of the manifest file of the last backed. 3247 } 3248 let infos: Array<string> = [ 3249 ` 3250 { 3251 "infos": [ 3252 { 3253 "details": [ 3254 { 3255 "detail": [ 3256 { 3257 "key1": "value1", 3258 "key2": "value2" 3259 } 3260 ] 3261 } 3262 ], 3263 "type": "unicast", 3264 "bundleName": "com.example.hiworld" 3265 } 3266 ] 3267 }, 3268 { 3269 "infos": [ 3270 { 3271 "details": [ 3272 { 3273 "detail": [ 3274 { 3275 "key1": "value1", 3276 "key2": "value2" 3277 } 3278 ] 3279 } 3280 ], 3281 "type": "unicast", 3282 "bundleName": "com.example.myApp" 3283 } 3284 ] 3285 } 3286 ` 3287 ] 3288 let incrementalBackupDataArray: backup.IncrementalBackupData[] = [incrementalBackupData]; 3289 // Appends the applications that require incremental backup. 3290 incrementalBackupSession.appendBundles(incrementalBackupDataArray, infos).then(() => { 3291 console.info('appendBundles success'); 3292 }).catch((err: BusinessError) => { 3293 console.error('appendBundles failed with err: ' + JSON.stringify(err)); 3294 }); 3295 ``` 3296### release<sup>12+</sup> 3297 3298release(): Promise<void> 3299 3300Releases the session for the incremental backup. This API uses a promise to return the result. 3301 3302**Required permissions**: ohos.permission.BACKUP 3303 3304**System capability**: SystemCapability.FileManagement.StorageService.Backup 3305 3306**Return value** 3307 3308| Type | Description | 3309| ------------------- | ----------------------- | 3310| Promise<void> | Promise that returns no value.| 3311 3312**Error codes** 3313 3314For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 3315 3316| ID| Error Message | 3317| -------- | ---------------------------------------------------------------------------------------------- | 3318| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 3319| 202 | Permission verification failed, application which is not a system application uses system API. | 3320| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 3321| 13600001 | IPC error. | 3322| 13900001 | Operation not permitted. | 3323| 13900005 | I/O error. | 3324| 13900020 | Invalid argument. | 3325| 13900042 | Unknown error. | 3326 3327**Example** 3328 3329 ```ts 3330 import fs from '@ohos.file.fs'; 3331 import { BusinessError } from '@ohos.base'; 3332 3333 let generalCallbacks: backup.GeneralCallbacks = { 3334 onFileReady: (err: BusinessError, file: backup.File) => { 3335 if (err) { 3336 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 3337 return; 3338 } 3339 console.info('onFileReady success'); 3340 fs.closeSync(file.fd); 3341 }, 3342 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 3343 if (err) { 3344 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3345 return; 3346 } 3347 console.info('onBundleBegin success'); 3348 }, 3349 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 3350 if (err) { 3351 console.error('onBundleBegin failed with err.code: ' + JSON.stringify(err.code) + err.data); 3352 return; 3353 } 3354 console.info('onBundleEnd success'); 3355 }, 3356 onAllBundlesEnd: (err: BusinessError) => { 3357 if (err) { 3358 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 3359 return; 3360 } 3361 console.info('onAllBundlesEnd success'); 3362 }, 3363 onBackupServiceDied: () => { 3364 console.info('service died'); 3365 }, 3366 onResultReport: (bundleName: string, result: string) => { 3367 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 3368 }, 3369 onProcess: (bundleName: string, process: string) => { 3370 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 3371 } 3372 }; 3373 let incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 3374 incrementalBackupSession.release(); // End the incremental backup process. 3375 console.info('release success'); 3376 ``` 3377 3378### cancel<sup>18+</sup> 3379 3380cancel(bundleName: string): number; 3381 3382Called to cancel the incremental backup of an application when data exceptions occur. 3383 3384**Required permissions**: ohos.permission.BACKUP 3385 3386**System capability**: SystemCapability.FileManagement.StorageService.Backup 3387 3388**Parameters** 3389 3390| Name | Type | Mandatory| Description | 3391| --------------- | -------- | ---- | -------------------------- | 3392| bundleName | string | Yes | Application name.| 3393 3394**Return value** 3395 3396| Type | Description | 3397| ------------------- | ----------------------- | 3398| number | Cancelled.<br>**0**: The task is successfully cancelled.<br> **13500011**: The task to be cancelled is not started.<br> **13500012**: The task to be cancelled does not exist.| 3399 3400**Error codes** 3401 3402For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md). 3403 3404| ID| Error Message | 3405| -------- | ---------------------------------------------------------------------------------------------- | 3406| 201 | Permission verification failed, usually the result returned by VerifyAccessToken. | 3407| 202 | Permission verification failed, application which is not a system application uses system API. | 3408| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verifcation faild.| 3409 3410**Example** 3411 3412 ```ts 3413 import fs from '@ohos.file.fs'; 3414 import { BusinessError } from '@ohos.base'; 3415 import backup from '@ohos.file.backup'; 3416 3417 incrementalBackupSession?: backup.IncrementalBackupSession; 3418 3419 let generalCallbacks: backup.GeneralCallbacks = { 3420 onFileReady: (err: BusinessError, file: backup.File) => { 3421 if (err) { 3422 // If the FD fails to be passed, call the cancel API to cancel the incremental backup task of the application. 3423 let result = this.incrementalBackupSession.cancel("com.example.myapplication"); 3424 console.info('cancel result:' + result); 3425 console.error('onFileReady failed with err: ' + JSON.stringify(err)); 3426 return; 3427 } 3428 console.info('onFileReady success'); 3429 fs.closeSync(file.fd); 3430 }, 3431 onBundleBegin: (err: BusinessError<string|void>, bundleName: string) => { 3432 if (err) { 3433 console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); 3434 return; 3435 } 3436 console.info('onBundleBegin success'); 3437 }, 3438 onBundleEnd: (err: BusinessError<string|void>, bundleName: string) => { 3439 if (err) { 3440 console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); 3441 return; 3442 } 3443 console.info('onBundleEnd success'); 3444 }, 3445 onAllBundlesEnd: (err: BusinessError) => { 3446 if (err) { 3447 console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); 3448 return; 3449 } 3450 console.info('onAllBundlesEnd success'); 3451 }, 3452 onBackupServiceDied: () => { 3453 console.info('service died'); 3454 }, 3455 onResultReport: (bundleName: string, result: string) => { 3456 console.info('onResultReport success, bundleName: ' + bundleName +'result: ' + result); 3457 }, 3458 onProcess: (bundleName: string, process: string) => { 3459 console.info('onProcess success, bundleName: ' + bundleName +'process: ' + process); 3460 } 3461 }; 3462 this.incrementalBackupSession = new backup.IncrementalBackupSession(generalCallbacks); // Create a session for an incremental backup. 3463 ``` 3464