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