How to Implement a Custom BackupExtensionAbility in HarmonyOS Next

SameX - Nov 3 - - Dev Community

This article aims to deeply explore the technical details of Huawei's HarmonyOS Next system (as of API 12 currently) and is summarized based on actual development practices.
As a carrier for technical sharing and exchange, it is inevitable that there may be errors and omissions. Colleagues are welcome to put forward valuable opinions and questions for common progress.
This article is original content. Any form of reprint must indicate the source and original author.


BackupExtensionAbility is a core component in the HarmonyOS Next system for implementing application data backup and restoration. By customizing the BackupExtensionAbility class and implementing the onBackup and onRestore methods, developers can define the operations that need to be performed during the data backup and restoration process of the application. This article will introduce in detail how to register and configure BackupExtensionAbility in HarmonyOS Next and show the basic process of its custom implementation.


I. Registration and Configuration File Description of BackupExtensionAbility

Before developing the backup and restoration function of the application, it is necessary to register BackupExtensionAbility in the configuration file so that the application can correctly access the backup and restoration framework of HarmonyOS Next.

1. Configure the module.json5 file

In the module.json5 configuration file, register BackupExtensionAbility by configuring the extensionAbilities field so that the system can recognize this class as a backup and restoration component. The specific configuration items are as follows:

  • type: Set to "backup" to indicate that this extension component is of backup and restoration type.
  • metadata: Add the "ohos.extension.backup" item to specify backup-related resources.
  • srcEntry: Specify the path of the BackupExtensionAbility class file.
{
  "extensionAbilities": [
    {
      "description": "$string:BackupExtensionAbilityDesc",
      "icon": "$media:app_icon",
      "name": "BackupExtensionAbility",
      "type": "backup",
      "exported": false,
      "metadata": [
        {
          "name": "ohos.extension.backup",
          "resource": "$profile:backup_config"
        }
      ],
      "srcEntry": "./ets/backupExtension/BackupExtension.ets"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

2. Configure the backup resource file

In the resources/base/profile folder, add a resource file that is consistent with the metadata.resource field in module.json5. This file is used to define which application data and resources need to be backed up, whether restoration is allowed, and other configurations.

The following is an example of the resource configuration file backup_config.json:

{
  "allowToBackupRestore": true,
  "includes": [
    "/data/storage/el2/base/files/"
  ],
  "excludes": [
    "/data/storage/el2/base/files/cache/"
  ],
  "fullBackupOnly": false
}
Enter fullscreen mode Exit fullscreen mode

The key fields in this file are explained as follows:

  • allowToBackupRestore: Whether backup and restoration are allowed.
  • includes: List of files or folders that need to be backed up.
  • excludes: List of files or folders that do not need to be backed up.
  • fullBackupOnly: Whether to perform full backup only.

II. Customize the BackupExtensionAbility Class

After configuration is completed, create and customize the BackupExtensionAbility class next. The specific backup and restoration logic is mainly defined by overriding the onBackup and onRestore methods.

  1. onBackup: This method is used to implement the data backup logic. In this method, you can specify the backup file path, data format, etc.
  2. onRestore: This method is used to implement the data restoration logic. After the device is upgraded or the application is reinstalled, the system will automatically call this method to restore the data in the backup directory to the application's sandbox directory.

The following is a basic implementation of the BackupExtensionAbility class:

import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';

const TAG = `BackupExtensionAbility`;

// Customize the BackupExtensionAbility class
export default class BackupExtension extends BackupExtensionAbility {
    // Data backup method
    onBackup() {
        console.log(TAG, `onBackup started, performing data backup...`);
        // Write data backup logic here, such as specifying backup path and format
    }

    // Data restoration method
    async onRestore(bundleVersion: BundleVersion): Promise<void> {
        console.log(TAG, `onRestore invoked with bundle version: ${JSON.stringify(bundleVersion)}`);
        if (bundleVersion.name.startsWith("0.0.0.0")) {
            console.log(TAG, `Performing data migration from HarmonyOS to HarmonyOS NEXT`);
            // Data migration processing logic
        } else {
            console.log(TAG, `Performing data restoration for other versions`);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

III. Mapping and Control of Backup and Restoration Data

In HarmonyOS Next, the application's data is usually stored in the application sandbox directory, and the backup and restoration framework will migrate this data to the backup directory. By configuring the includes and excludes fields, developers can flexibly control which data needs to be backed up and the restoration path of the backed up data.

1. Data directory mapping

In application data backup, the mapping relationship of the following common directories is:

Application data directory Backup and restoration directory Acquisition method
/data/user_de/{userId}/{package name}/ /data/storage/el1/base/.backup/restore/{package name}/de/ contextConstant.AreaMode.EL1
/data/user/{userId}/{package name}/ /data/storage/el2/base/.backup/restore/{package name}/ce/ contextConstant.AreaMode.EL2
/data/media/{userId}/Android/data/{package name}/ /data/storage/el2/base/.backup/restore/{package name}/A/data/ contextConstant.AreaMode.EL2

2. Data storage and restoration path control

Through the context object this.context of BackupExtensionAbility, the backup and restoration directory can be directly obtained. When implementing onBackup and onRestore, developers can use the following code to read and restore backup data:

const deSourcePath = `${this.context.backupDir}restore/{package name}/de/`;
const ceSourcePath = `${this.context.backupDir}restore/{package name}/ce/`;
Enter fullscreen mode Exit fullscreen mode

IV. Example Code: Implementation of onBackup and onRestore

The following code example shows how to implement data backup and restoration logic in the onBackup and onRestore methods. This example demonstrates backing up the data of a specified folder and performing specific restoration operations for different system versions during the data restoration process.

import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG = `FileBackupExtensionAbility`;

// Custom implementation of BackupExtensionAbility
export default class BackupExtension extends BackupExtensionAbility {
    // Data backup logic
    async onBackup(): Promise<void> {
        hilog.info(0x0000, TAG, `onBackup invoked, starting data backup process...`);

        // Get backup directory
        const backupPath = this.context.backupDir + "files/";
        try {
            // Execute backup logic
            hilog.info(0x0000, TAG, `Backing up data to path: ${backupPath}`);
            // Assume backup data to the specified directory. Developers can implement file copying, packaging and other operations here.
        } catch (error) {
            hilog.error(0x0000, TAG, `Error during backup: ${error.message}`);
        }
    }

    // Data restoration logic
    async onRestore(bundleVersion: BundleVersion): Promise<void> {
        hilog.info(0x0000, TAG, `onRestore invoked for bundle version: ${JSON.stringify(bundleVersion)}`);

        if (bundleVersion.name.startsWith("0.0.0.0")) {
            hilog.info(0x0000, TAG, `HarmonyOS to HarmonyOS NEXT upgrade detected, handling data migration.`);
            // Implement data migration logic
            const restorePath = `${this.context.backupDir}restore/{package name}/de/`;
            hilog.info(0x0000, TAG, `Restoring data from path: ${restorePath}`);
            // Load data from the restoration directory to the sandbox directory
        } else {
            hilog.info(0x0000, TAG, `Standard restore for other versions.`);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code:

  • The onBackup method defines the backup path and stores the application data in the backup directory.
  • The onRestore method executes the restoration logic according to bundleVersion and supports data migration from the old version of HarmonyOS to HarmonyOS NEXT.

Summary

By customizing the BackupExtensionAbility class, the backup and restoration framework of HarmonyOS Next can flexibly handle the backup and restoration of application data. We can set the backup path and filtering conditions of data according to business needs and execute custom data migration strategies in the data restoration stage.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player