Integrate the HarmonyOS SDK

Updated at:

This topic describes how to integrate the HarmonyOS SDK.

Preface

This software development kit (SDK) is based on HarmonyOS API 12, with a compatibleSdkVersion of 5.0.0(12).

Preparations

  1. Prepare a HarmonyOS application development environment. For more information, see HarmonyOS Application Development Guide.

  2. Create a HarmonyOS application and obtain its AppKey and AppSecret from the application settings. For more information, see Integrate an SDK.

Step 1: Install the SDK

In the root directory of your HarmonyOS application, execute the following commands to install the SDK:

ohpm install @aliyun/apm
ohpm install @aliyun/apm_perf

For more information about the ohpm tool and how to install third-party SDKs for OpenHarmony, see OpenHarmony Third-party Library Repository Guide.

Step 2: Initialize the SDK and start performance analysis

In the Ability onCreate lifecycle callback, execute the following code to initialize and configure the SDK:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { APM, APMConfig, Logger } from '@aliyun/apm';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { performanceApi } from '@aliyun/apm_perf';

class MyCustomLog implements Logger {
  print(domain: number, tag: string, level: hilog.LogLevel, msg: string): void {
    switch (level) {
      case hilog.LogLevel.DEBUG:
        console.debug(`Custom log msg:${msg}`);
        break;
      case hilog.LogLevel.INFO:
        console.info(`Custom log msg:${msg}`);
        break;
      case hilog.LogLevel.WARN:
        console.warn(`Custom log msg:${msg}`);
        break;
      case hilog.LogLevel.ERROR:
      case hilog.LogLevel.FATAL:
        console.error(`Custom log msg:${msg}`);
        break;
    }
  }
}

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');

    const apm_perf_config: APMConfig = {
      context: this.context,
      appKey: 'Your AppKey',
      appSecret: 'Your AppSecret',
      nick: 'User nickname',
      userId: 'User ID',
      channel: 'User channel',
      hiLog: true, // The switch for hilog in the SDK
      customLogger: new MyCustomLog(), // Custom log interface
    }
    APM.init(apm_perf_config, [performanceApi])
    APM.start();

  }

  // Other code is omitted.
}

Set appKey and appSecret to the AppKey and AppSecret that you obtained in the Preparations section.

Step 3: Verify the integration

After integrating the SDK, start the application and navigate between a few pages. Then, move the application to the background. Wait for 3 minutes and check the console to verify that application data is reported.