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