Integrate the HarmonyOS SDK

更新时间:
复制 MD 格式

This topic describes how to integrate the HarmonyOS SDK.

Foreword

This software development kit (SDK) is based on HarmonyOS API 12 Release and uses a compileSdkVersion of 5.0.0(12).

Preparations

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

  2. Create a HarmonyOS application and obtain the AppKey and AppSecret from the application settings. For more information, see Native application development process.

  3. Configure the application to obtain a HarmonyOS Push Token. For more information, see HarmonyOS Push Kit Development Preparations.

  4. Implement the application authorization request logic. For more information, see Request notification authorization.

  5. To push notification extension messages, request the required permissions. For more information, see Send notification extension messages.

Step 1: Install the SDK

You can run the following command in the root directory of your HarmonyOS application to install the SDK:

ohpm install @aliyun/push

For more information about the ohpm tool and installing third-party SDKs for OpenHarmony, see OpenHarmony Third-Party Library Central Repository Guide.

For the latest SDK version and update history, see SDK information and Update history.

Step 2: Initialize the SDK

Run the following code in the `onCreate` lifecycle callback of the Ability to initialize and configure the SDK:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { aliyunPush } from '@aliyun/push';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    // ************* Initialize configuration: start *************
    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained in the Preparations step',
      appSecret: 'Enter the AppSecret that you obtained in the Preparations step',
      context: this.context,
    })
    // ************* Initialize configuration: end *************
  }

  // Other code is omitted
}

Set `appKey` and `appSecret` to the values that you obtained in the Preparations step.

Note

Configuration for persistent background connections

Default behavior

By default, the HarmonyOS Push SDK disconnects the persistent connection when the application moves to the background. As a result, the device immediately enters an offline state.

Configuration options (v1.2.4+)

Starting from version 1.2.4, the SDK provides the allowBackgroundConnection option to control the behavior of persistent background connections:

  • Default value: false - The persistent connection is automatically disconnected when the application is in the background.

  • Optional value: true - The persistent connection is maintained when the application is in the background.

Requirements

If you set allowBackgroundConnection = true, the following condition must be met:

Notes

⚠️ Important: If you enable persistent background connections but do not request the required permissions, the device may enter a "false online" state for about 30 seconds:

  • The device does not actively disconnect after moving to the background.

  • However, the application task is frozen by the system and cannot process push messages.

Step 3: Set the push callback interface

After you initialize the SDK, set the push callback interface in the `onCreate` callback method of the UIAbility to receive push data. The following code provides an example:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { aliyunPush, ExtensionNotification, IPushListener, PushMessage, PushNotification } from '@aliyun/push';

// ************* IPushListener interface implementation: start *************
/**
 * Implements the push callback interface to receive push data.
 */
class MyPushListener implements IPushListener {

  onReceiveNotification(data: PushNotification | ExtensionNotification): boolean {
    // Process the push notification.
    // Return false to use the default notification. Return true to customize the notification.
    return false;
  }

  onShowNotification(data: PushNotification | ExtensionNotification): void {
    // Process the notification display event.
  }

  onReceiveMessage(data: PushMessage): void {
    // Process the push message.
  }
}
// ************* IPushListener interface implementation: end *************

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained during the SDK integration preparations',
      appSecret: 'Enter the AppSecret that you obtained during the SDK integration preparations',
      context: this.context,
    })

    // ************* Register the IPushListener interface: start *************
    aliyunPush.setPushListener(new MyPushListener());
    // ************* Register the IPushListener interface: end *************
  }

  // Other code is omitted

  onDestroy(): void {
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability

    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        return;
      }
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
  }

  onForeground(): void {
    // Ability has brought to foreground
  }

  onBackground(): void {
    // Ability has back to background
  }
}

For more information about the push callback interface, see Receive push notifications and messages.

Step 4: Call the notification click handler interface

Call the `handleClickNotification` method of the SDK to handle user clicks on notifications and retrieve push data. Call this method in two places:

  1. In the `onCreate` callback method of the UIAbility, after you initialize the SDK

  2. In the `onNewWant` callback method of the UIAbility

The following code provides an example:

import { aliyunPush, Channel,
  ExtensionNotification,
  PushMessage, PushNotification, PushNotificationHandler } from '@aliyun/push';
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';

// ************* Custom class for processing push data: start *************
class MyPushNotificationHandler implements PushNotificationHandler {
  onClickNotification(data: PushNotification | PushMessage | ExtensionNotification, from: Channel): void {
    // Process push data as needed.
  }

  noPushData(): void {
    // No push data. The interface was not launched by a user clicking a push notification.
  }
}
// ************* Custom class for processing push data: end *************

// The Ability to open when a notification is clicked.
export class TargetAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    // ************* Initialize Push: start *************
    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained in the Preparations step',
      appSecret: 'Enter the AppSecret that you obtained in the Preparations step',
      context: this.context,
    })
    // ************* Initialize Push: end *************

    // ************* Process push data: start *************
    aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
    // ************* Process push data: end *************

  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    // Scenario where the page is already started.
    // ************* Process push data: start *************
    aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
    // ************* Process push data: end *************
  }

  // Other code is omitted
}

For more information about the `handleClickNotification` method, see Retrieve push data from notifications.

Step 5: Register the device to get the device ID

In the `onCreate` callback method of the UIAbility, after you initialize the SDK, call the `register` method of the SDK to register the device.

Device registration is a required step for push notifications. After the device is registered, you can request to register the HarmonyOS PushToken and call APIs to perform operations such as attaching an account, adding an alias, or attaching a tag.

The following code provides an example:

import { aliyunPush } from '@aliyun/push';

aliyunPush.register((err) => {
  if (err) {
    console.error(`Failed to register the device. Error code: ${err.code}. Error message: ${err.message}`);
    return;
  }
  console.info(`The device is registered. Device ID: ${aliyunPush.getDeviceId()}`);
});

After the device is registered, the SDK establishes a persistent connection with the server. You can then call the `getDeviceId` method to obtain the device ID and send pushes to the application that target a specific device from the console or using OpenAPI.

Step 6: Register the HarmonyOS PushToken (Optional)

To use the HarmonyOS third-party channel, you must use the SDK to register the HarmonyOS PushToken with the Mobile Push platform. Call this method after the device is registered. The following code provides an example:

import { aliyunPush } from '@aliyun/push';
import { pushService } from '@kit.PushKit';
import { BusinessError } from '@kit.BasicServicesKit';

pushService.getToken().then((pushToken) => {
  // ************* Register PushToken: start *************
  aliyunPush.registerThirdToken(pushToken, (error) => {
    if (error) {
      console.error(`Failed to register the PushToken. Error code: ${error.code}. Error message: ${error.message}`);
      return;
    }
    console.info(`The PushToken is registered.`);
  })
  // ************* Register PushToken: end *************
}).catch((error: BusinessError) => {
  console.error(`Failed to get the PushToken. Error code: ${error.code}. Error message: ${error.message}`);
})

For more information about the HarmonyOS third-party channel, see Third-party channels.

Step 7: Implement the reception of notification extension messages for the HarmonyOS channel (Optional)

If you have integrated the HarmonyOS third-party channel and want to push notification extension messages, you must call the SDK interface to parse and retrieve the push data when a notification extension message is received. You can then perform subsequent operations.

The following code shows an example of how `RemoteNotificationExtensionAbility` processes a received notification extension message:

import { pushCommon, RemoteNotificationExtensionAbility } from '@kit.PushKit';
import { aliyunPush, ExtensionNotification } from '@aliyun/push';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';

export default class SampleRemoteNotification extends RemoteNotificationExtensionAbility {
  async onReceiveMessage(remoteNotificationInfo: pushCommon.RemoteNotificationInfo):
    Promise<pushCommon.RemoteNotificationContent> {
    // ************* Process notification extension message: start *************
    // Initialize push parameters to parse push data.
    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained in the Preparations step',
      appSecret: 'Enter the AppSecret that you obtained in the Preparations step',
      context: this.context as common.Context,
    })

    // Call parseExtensionPushData to parse the push parameters.
    const notification: ExtensionNotification = await aliyunPush.parseExtensionPushData(remoteNotificationInfo);

    // Here, you can get the parameters of the notification extension message for business processing.

    // The SDK provides the getRemoteNotificationContent helper method to construct the return value. The EntryAbility parameter is the name of the Ability to open when this notification is clicked.
    const result = aliyunPush.getPushHelper().getRemoteNotificationContent('EntryAbility', notification);
    return result;
    // If you want to modify the notification content, you can return the desired content. We recommend that you retain the wantAgent. If you do not retain it, the push parameters cannot be identified when the user clicks the notification, and the notification click data will be lost.
    // return {
    //   // Other modified fields are omitted. We recommend that you use the parameters constructed by the getRemoteNotificationContent method for wantAgent.
    //   wantAgent: result.wantAgent
    // }
    // ************* Process notification extension message: end *************
  }
}

The following code shows an example of how `pushService.receiveMessage` processes a received notification extension message:

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    // ************* Initialize SDK: start *************
    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained in the Preparations step',
      appSecret: 'Enter the AppSecret that you obtained in the Preparations step',
      context: this.context,
    })
    // ************* Initialize SDK: end *************

    // Other initialization configuration methods are omitted.

    // ************* Set the interface for receiving notification extension messages from the HarmonyOS channel when the application is in the foreground: start *************
    pushService.receiveMessage("IM", this, async (data: pushCommon.PushPayload) => {
      // Parse the push parameters.
      const extensionNotification: ExtensionNotification = await aliyunPush.parseExtensionPushData(data);
      // Process business logic based on the obtained parameters of the notification extension message.
    })
    // ************* Set the interface for receiving notification extension messages from the HarmonyOS channel when the application is in the foreground: end *************
  }
  // Other code is omitted
}

For more information about changes to `RemoteNotificationExtensionAbility` and `pushService.receiveMessage`, see Development steps for notification extension messages.

For more information about how to use the Alibaba Cloud Mobile Push platform to send notification extension messages, see Notification extension messages.

Step 8: Send a push

You can send a push to a device from the console using Push Notification or Push Message, or using the Push-related APIs of OpenAPI. After the SDK receives the push, it calls the callback interface that you set in Step 3: Set the push callback interface.

When a push notification is received, the SDK calls the `onReceiveNotification` method to notify the application. After the SDK creates and publishes the notification, it calls the `onShowNotification` method to notify the application that the notification was published.

When a push message is received, the SDK calls the `onReceiveMessage` method to notify the application.

Compliance and delayed initialization

The SDK uses the following permissions:

Permission name

Permission description

Purpose

When to request

ohos.permission.INTERNET

Allows the use of the internet.

Used to access network data when establishing a push channel.

The system automatically grants this permission during application installation.

ohos.permission.GET_NETWORK_INFO

Allows the application to get data network information.

Used to listen for network changes when managing the push channel and instantly recover the push channel when the network is restored.

The system automatically grants this permission during application installation.

The preceding permissions are automatically granted by the system during installation. Therefore, the SDK does not need to actively request permissions from the user.

For notification authorization, you must implement the logic to request authorization from the user. For more information, see Request notification authorization. By default, the SDK does not request this authorization.

For information about the SDK and the privacy policy, see SDK information.

Before the user agrees to your application's privacy policy and grants notification authorization, you should consider delaying the SDK initialization. We recommend the following approach:

For a code example, see Complete code example for SDK integration.

Complete code example for SDK integration

The following code provides a complete example to help you understand the execution order of the SDK integration steps:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import {
  aliyunPush,
  Channel,
  ExtensionNotification,
  IPushListener,
  PushDataType,
  PushMessage,
  PushNotification,
  PushNotificationHandler
} from '@aliyun/push';
import { pushCommon, pushService } from '@kit.PushKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

/**
 * Custom implementation of the push callback interface.
 */
class MyPushListener implements IPushListener {
  onReceiveNotification(data: PushNotification | ExtensionNotification): boolean {
    if (data.type === PushDataType.Notification) {
      // Process the push notification.
    } else if (data.type === PushDataType.ExtensionNotification) {
      // Process the notification extension message.
    }
    return false;
  }

  onShowNotification(data: PushNotification | ExtensionNotification): void {
    // Process the notification display event.
  }

  onReceiveMessage(data: PushMessage): void {
    // Process the push message.
  }
}

/**
 * Custom class for processing push data.
 */
class MyPushNotificationHandler implements PushNotificationHandler {
  onClickNotification(data: PushNotification | PushMessage | ExtensionNotification, from: Channel): void {
    // The page is launched by a user clicking a notification. Get the push data and process the business logic.
  }

  noPushData(): void {
    // The page was not launched by a user clicking a notification, or the data is not from Alibaba Cloud Mobile Push.
  }
}

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    // ************* Initialize SDK: start *************
    aliyunPush.init({
      appKey: 'Enter the AppKey that you obtained in the Preparations step',
      appSecret: 'Enter the AppSecret that you obtained in the Preparations step',
      context: this.context,
    })
    // ************* Initialize SDK: end *************

    // ************* Set the push callback interface: start *************
    aliyunPush.setPushListener(new MyPushListener());
    // ************* Set the push callback interface: end *************

    // ************* Call the notification click handler interface: start *************
    aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
    // ************* Call the notification click handler interface: end *************

    // Here, the application needs to get a flag indicating whether the user has agreed to use the SDK.
    const userAgreed = false;
    if(userAgreed) {
      // Initialize and register for push notifications only after the user agrees.
      this.registerPush();
    }

    // ************* Set the interface for receiving notification extension messages from the HarmonyOS channel when the application is in the foreground: start *************
    pushService.receiveMessage("IM", this, async (data: pushCommon.PushPayload) => {
      // Parse the push parameters.
      const extensionNotification: ExtensionNotification = await aliyunPush.parseExtensionPushData(data);
      // Process business logic based on the obtained parameters of the notification extension message.
    })
    // ************* Set the interface for receiving notification extension messages from the HarmonyOS channel when the application is in the foreground: end *************
  }

  /**
   * This method can be delayed until after the user agrees to use the SDK.
   */
  private async registerPush() {
    // ************* Register the device to get the device ID: start *************
    await aliyunPush.register();
    const deviceId = aliyunPush.getDeviceId();
    // ************* Register the device to get the device ID: end *************

    const pushToken = await pushService.getToken();
    // ************* Register the HarmonyOS PushToken: start *************
    await aliyunPush.registerThirdToken(pushToken);
    // ************* Register the HarmonyOS PushToken: end *************
  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    // ************* Call the notification click handler interface: start *************
    aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
    // ************* Call the notification click handler interface: end *************
  }

  // Other code is omitted

  onDestroy(): void {
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability

    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        return;
      }
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
  }

  onForeground(): void {
    // Ability has brought to foreground
  }

  onBackground(): void {
    // Ability has back to background
  }
}

What to do next

If you want to send pushes by alias or tag, or customize notification styles, see HarmonyOS SDK API.