• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.application.BackupExtensionAbility (备份恢复扩展能力)
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @lvzhenjie-->
5<!--Designer: @wang_zhangjun; @chenxi0605-->
6<!--Tester: @liuhonggang123-->
7<!--Adviser: @foryourself-->
8
9BackupExtensionAbility模块提供备份恢复服务相关扩展能力,为应用提供扩展的备份恢复能力。
10
11> **说明:**
12>
13> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
14>
15> - 本模块接口仅可在Stage模型下使用。
16
17## 导入模块
18
19```ts
20import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
21```
22
23## BundleVersion
24
25恢复时所需要的版本信息,开发者可根据配置的版本号来判断本次恢复时的应用版本数据。
26
27**系统能力**:SystemCapability.FileManagement.StorageService.Backup
28
29| 名称 | 类型   | 只读 | 可选 | 说明             |
30| ---- | ------ | ---- | --- | ---------------- |
31| code | number | 否   | 否  | 应用的版本号。   |
32| name | string | 否   | 否  | 应用的版本名称。 |
33
34## BackupExtensionAbility
35
36应用接入数据备份恢复需要通过BackupExtensionAbility实现,开发者可以通过[onBackup](#onbackup),[onRestore](#onrestore)来实现自定义的备份恢复操作。
37
38### 属性
39
40**系统能力**:SystemCapability.FileManagement.StorageService.Backup
41
42| 名称                  | 类型                                                              | 只读 | 可选 | 说明                                                |
43| --------------------- | ----------------------------------------------------------------- | ---- | --- | --------------------------------------------------- |
44| context<sup>11+</sup> | [BackupExtensionContext](js-apis-file-backupextensioncontext.md) | 否  | 否 | BackupExtensionAbility的上下文环境,继承自[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md)。 |
45
46### onBackup
47
48onBackup(): void
49
50Extension生命周期回调,在执行备份数据时回调,由开发者提供扩展的备份数据的操作。
51
52**系统能力**:SystemCapability.FileManagement.StorageService.Backup
53
54**示例:**
55
56  ```ts
57  class BackupExt extends BackupExtensionAbility {
58    async onBackup() {
59      console.log('onBackup');
60    }
61  }
62  ```
63
64### onBackupEx<sup>12+</sup>
65
66onBackupEx(backupInfo: string): string | Promise&lt;string&gt;
67
68备份恢复框架增加扩展参数,允许应用备份、恢复时传递参数给应用。支持异步操作,使用Promise异步回调。<br>
69onBackupEx与onBackup互斥,如果重写onBackupEx,则优先调用onBackupEx。<br>
70onBackupEx返回值不能为空字符串,若onBackupEx返回值为空字符串,则会尝试调用onBackup。
71
72**系统能力**:SystemCapability.FileManagement.StorageService.Backup
73
74**参数:**
75
76| 参数名           | 类型                            | 必填 | 说明                          |
77|---------------| ------------------------------- | ---- |-----------------------------|
78| backupInfo    |string | 是   | 扩展恢复数据的特殊处理接口中三方应用需要传递的包信息。<br>backupInfo可能为空字符串,需要开发者针对空字符串场景做判断处理。 |
79
80**返回值:**
81
82| 类型                            | 说明    |
83| ----------------------------- | :---- |
84|string \| Promise&lt;string&gt; |返回应用执行自定义备份操作的信息,包含备份结果和报错信息,返回值为Json格式。<br>异步返回Promise对象。<br>同步返回string。 |
85
86> **说明:**
87>
88> 同步处理业务场景中,推荐使用示例如下。
89
90**示例:**
91
92```ts
93import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
94
95interface ErrorInfo {
96  type: string,
97  errorCode: number,
98  errorInfo: string
99}
100class BackupExt extends BackupExtensionAbility {
101  onBackupEx(backupInfo: string): string {
102    try {
103      if (backupInfo == "") {
104        //当backupInfo为空时,应用根据业务自行做处理。
105        console.info("backupInfo is empty");
106      }
107      console.log(`onBackupEx ok`);
108      let errorInfo: ErrorInfo = {
109        type: "ErrorInfo",
110        errorCode: 0,
111        errorInfo: "app customized error info"
112      }
113      return JSON.stringify(errorInfo);
114    } catch (err) {
115      console.error(`BackupExt error. Code:${err.code}, message:${err.message}`);
116    }
117    return "";
118  }
119}
120```
121
122> **说明:**
123>
124> 异步处理业务场景中,推荐使用示例如下。
125
126**示例:**
127
128```ts
129import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
130
131interface ErrorInfo {
132  type: string,
133  errorCode: number,
134  errorInfo: string
135}
136class BackupExt extends BackupExtensionAbility {
137  //异步实现
138  async onBackupEx(backupInfo: string): Promise<string> {
139    try {
140      if (backupInfo == "") {
141        //当backupInfo为空时,应用根据业务自行做处理。
142        console.info("backupInfo is empty");
143      }
144      console.log(`onBackupEx ok`);
145      let errorInfo: ErrorInfo = {
146        type: "ErrorInfo",
147        errorCode: 0,
148        errorInfo: "app customized error info"
149      }
150      return JSON.stringify(errorInfo);
151    } catch (err) {
152      console.error(`BackupExt error. Code:${err.code}, message:${err.message}`);
153    }
154    return "";
155  }
156}
157```
158
159### onRestore
160
161onRestore(bundleVersion: BundleVersion): void
162
163Extension生命周期回调,在执行恢复数据时回调,由开发者提供扩展的恢复数据的操作。
164
165**系统能力**:SystemCapability.FileManagement.StorageService.Backup
166
167**参数:**
168
169| 参数名        | 类型                            | 必填 | 说明                           |
170| ------------- | ------------------------------- | ---- | ------------------------------ |
171| bundleVersion | [BundleVersion](#bundleversion) | 是   | 恢复时应用数据所在的版本信息。 |
172
173**示例:**
174
175  ```ts
176  import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
177
178  class BackupExt extends BackupExtensionAbility {
179    async onRestore(bundleVersion : BundleVersion) {
180      console.log(`onRestore ok ${JSON.stringify(bundleVersion)}`);
181    }
182  }
183  ```
184
185### onRestoreEx<sup>12+</sup>
186
187onRestoreEx(bundleVersion: BundleVersion, restoreInfo: string): string | Promise&lt;string&gt;
188
189Extension生命周期回调,在执行恢复数据时回调,由开发者提供扩展的恢复数据的操作,支持异步操作,使用Promise异步回调。<br>
190onRestoreEx与onRestore互斥,如果重写onRestoreEx,则优先调用onRestoreEx。<br>
191onRestoreEx返回值不能为空字符串,若onRestoreEx返回值为空字符串,则会尝试调用onRestore。<br>
192onRestoreEx的返回值为Json格式,使用方法见示例代码。
193
194**系统能力**:SystemCapability.FileManagement.StorageService.Backup
195
196**参数:**
197
198| 参数名        | 类型                            | 必填 | 说明                           |
199| ------------- | ------------------------------- | ---- | ------------------------------ |
200| bundleVersion | [BundleVersion](#bundleversion) | 是   | 恢复时应用数据所在的版本信息。 |
201| restoreInfo |string | 是   | 预留字段,应用恢复过程中需要的扩展参数。<br>restoreInfo可能为空字符串,需要开发者针对空字符串场景做判断处理。 |
202
203**返回值:**
204
205| 类型                            | 说明    |
206| ----------------------------- | :---- |
207| string \| Promise&lt;string&gt; |返回应用执行自定义恢复操作的信息,包含恢复结果和报错信息,返回值为Json格式。<br>异步返回Promise对象。<br>同步返回string。 |
208
209> **说明:**
210>
211> 异步处理业务场景中,推荐使用示例如下。
212
213**示例:**
214
215```ts
216import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
217interface ErrorInfo {
218  type: string,
219  errorCode: number,
220  errorInfo: string
221}
222class BackupExt extends BackupExtensionAbility {
223  // 异步实现
224  async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> {
225    try {
226      if (restoreInfo == "") {
227        //当restoreInfo为空时,应用根据业务自行做处理。
228        console.info("restoreInfo is empty");
229      }
230      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
231      let errorInfo: ErrorInfo = {
232        type: "ErrorInfo",
233        errorCode: 0,
234        errorInfo: "app customized error info"
235      }
236      return JSON.stringify(errorInfo);
237    } catch (err) {
238      console.error(`onRestoreEx error. Code:${err.code}, message:${err.message}`);
239    }
240    return "";
241  }
242}
243```
244
245> **说明:**
246>
247> 同步处理业务场景中,推荐使用示例如下。
248
249**示例:**
250
251```ts
252import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
253interface ErrorInfo {
254  type: string,
255  errorCode: number,
256  errorInfo: string
257}
258
259class BackupExt extends BackupExtensionAbility {
260  // 同步实现
261  onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): string {
262    try {
263      if (restoreInfo == "") {
264        //当restoreInfo为空时,应用根据业务自行做处理。
265        console.info("restoreInfo is empty");
266      }
267      console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
268      let errorInfo: ErrorInfo = {
269        type: "ErrorInfo",
270        errorCode: 0,
271        errorInfo: "app customized error info"
272      }
273      return JSON.stringify(errorInfo);
274    } catch (err) {
275      console.error(`onRestoreEx error. Code:${err.code}, message:${err.message}`);
276    }
277    return "";
278  }
279}
280
281```
282
283### onProcess<sup>12+</sup>
284
285onProcess(): string
286
287备份恢复框架增加进度返回接口。该接口为同步接口,由应用在执行onBackup(onBackupEx)/onRestore(onRestoreEx)期间进行实现。返回应用自身处理业务的进度,返回值为json结构,使用方法见示例代码。
288
289**系统能力**:SystemCapability.FileManagement.StorageService.Backup
290
291**返回值:**
292
293| 类型                   | 说明    |
294| --------------------- | :---- |
295| string |返回应用onBackup或者onRestore执行过程中处理数据的进度信息(返回值为Json格式)。|
296
297> **说明:**
298>
299> - onProcess可以不实现,系统有默认处理机制;若要实现,返回值结构严格按照示例代码返回。
300> - 实现onProcess时,业务需要将onBackup(onBackupEx)/onRestore(onRestoreEx)做异步实现,且需要单独开辟子线程,否则onProcess相关功能无法正常运行。具体使用方式见示例代码。
301> - onProcess()推荐使用示例如下。
302
303**示例:**
304
305  ```ts
306  import { BackupExtensionAbility } from '@kit.CoreFileKit';
307  import { taskpool } from '@kit.ArkTS';
308
309  @Sendable
310  class MigrateProgressInfo {
311    private migrateProgress: string = '';
312    private name: string = "test"; // appName
313    private processed: number = 0; // 已处理的数据
314    private total: number = 100; // 总数
315    private isPercentage: boolean = true // 可选字段,true表示需要按百分比的格式化展示进度,false或者不实现该字段表示按具体项数展示进度
316
317    getMigrateProgress(): string {
318      this.migrateProgress = `{"progressInfo": [{"name": "${this.name}", "processed": "${this.processed}", "total": "${
319        this.total}", "isPercentage": "${this.isPercentage}"}]}`;
320      return this.migrateProgress;
321    }
322
323    updateProcessed(processed: number) {
324      this.processed = processed;
325    }
326  }
327
328  class BackupExt extends BackupExtensionAbility {
329    private progressInfo: MigrateProgressInfo = new MigrateProgressInfo();
330
331    // 如下代码中,appJob方法为模拟的实际业务代码,args为appJob方法的参数,用于提交到taskpool中,开启子线程进行工作
332    async onBackup() {
333      console.log(`onBackup begin`);
334      let args = 100; // args为appJob方法的参数
335      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, this.progressInfo, args);
336      try {
337        await taskpool.execute(jobTask, taskpool.Priority.LOW);
338      } catch (error) {
339        console.error("onBackup error." + error.message);
340      }
341      taskpool.terminateTask(jobTask); // 需要手动销毁
342      console.log(`onBackup end`);
343    }
344
345    async onRestore() {
346      console.log(`onRestore begin`);
347      let args = 100; // args为appJob方法的参数
348      let jobTask: taskpool.Task = new taskpool.LongTask(appJob, this.progressInfo, args);
349      try {
350        await taskpool.execute(jobTask, taskpool.Priority.LOW);
351      } catch (error) {
352        console.error("onRestore error." + error.message);
353      }
354      taskpool.terminateTask(jobTask); // 需要手动销毁
355      console.log(`onRestore end`);
356    }
357
358
359    onProcess(): string {
360      console.log(`onProcess begin`);
361      return this.progressInfo.getMigrateProgress();
362    }
363  }
364
365  @Concurrent
366  function appJob(progressInfo: MigrateProgressInfo, args: number) : string {
367    console.log(`appJob begin, args is: ` + args);
368    // 在业务执行时刷新已处理进度
369    let currentProcessed: number = 0;
370    // 模拟业务实际逻辑
371    for (let i = 0; i < args; i++) {
372      currentProcessed = i;
373      progressInfo.updateProcessed(currentProcessed);
374    }
375    return "ok";
376  }
377  ```
378
379### onRelease<sup>20+</sup>
380
381onRelease(scenario: number): Promise&lt;void&gt;
382
383备份恢复框架安全退出接口。应用备份或恢复完成时回调,应用可实现备份恢复完成后的一些特殊处理,例如清理备份或恢复产生的临时文件。使用Promise异步回调。<br>
384onRelease具有超时机制,应用若在5秒内未完成onRelease操作,将触发备份恢复结束时的应用进程退出流程。
385
386**系统能力**:SystemCapability.FileManagement.StorageService.Backup
387
388**参数:**
389
390| 参数名        | 类型                            | 必填 | 说明                           |
391| ------------- | ------------------------------- | ---- | ------------------------------ |
392| scenario | number | 是   | 表示处于备份或恢复场景。<br>scenario = 1表示当前为备份场景。<br>scenario = 2表示当前为恢复场景。|
393
394**返回值:**
395
396| 类型                   | 说明    |
397| --------------------- | :---- |
398| Promise&lt;void&gt; | Promise对象,无返回结果。|
399
400**示例:**
401
402```ts
403// 以清理文件为例
404import { BackupExtensionAbility, fileIo } from '@kit.CoreFileKit';
405
406const SCENARIO_BACKUP: number = 1;
407const SCENARIO_RESTORE: number = 2;
408// 需要清理的临时目录
409let filePath: string = '/data/storage/el2/base/.temp/';
410
411class BackupExt extends BackupExtensionAbility {
412  async onRelease(scenario: number): Promise<void> {
413    try {
414      if (scenario == SCENARIO_BACKUP) {
415        // 备份场景,应用自行实现处理,以清理备份产生的临时文件为例
416        console.info(`onRelease begin`);
417        await fileIo.rmdir(filePath);
418        console.info(`onRelease end, rmdir succeed`);
419      }
420      if (scenario == SCENARIO_RESTORE) {
421        // 恢复场景,应用自行实现处理,以清理恢复产生的临时文件为例
422        console.info(`onRelease begin`);
423        await fileIo.rmdir(filePath);
424        console.info(`onRelease end, rmdir succeed`);
425      }
426    } catch (error) {
427      console.error(`onRelease failed with error. Code: ${error.code}, message: ${error.message}`);
428    }
429  }
430}
431```