This topic describes how to use the HarmonyOS software development kit (SDK) to receive and process push notifications and messages.
Feature description
When a device is online, the Alibaba Cloud channel sends pushes to the SDK. The SDK provides the IPushListener interface to receive push data.
When a notification is sent, the SDK calls the relevant callback method, passes the notification data to the application, creates a notification, and displays it in the device's notification bar. When a user taps the notification to open an Ability, the SDK provides a method to retrieve the notification data.
When a message is sent, the SDK calls the relevant callback method and passes the message data to the application.
When you integrate the SDK, the application must register the IPushListener interface.
Receive push notifications or messages
When you integrate the SDK, you can register the IPushListener interface to receive push data. The following code shows an example:
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { aliyunPush, IPushListener, PushMessage, PushNotification } from '@aliyun/push';
// ************* IPushListener interface implementation begin *************
/**
* Push callback interface implementation for receiving push data
*/
class MyPushListener implements IPushListener {
onReceiveNotification(data: PushNotification): boolean {
// Process the push notification.
// Return false to not customize the notification. Return true to customize the notification.
return false;
}
onShowNotification(data: PushNotification): 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 queried in the SDK integration preparations.',
appSecret: 'Enter the AppSecret that you queried in the SDK integration preparations.',
context: this.context,
})
// ************* Register the IPushListener interface begin *************
aliyunPush.setPushListener(new MyPushListener());
// ************* Register the IPushListener interface end *************
}
// Other code is omitted.
}
Registering the IPushListener interface is part of the SDK integration flow. For a complete code example, see Complete SDK integration code example.
Receive push notifications
When the SDK receives a push notification, it calls the onReceiveNotification callback method. The PushNotification parameter contains the parameters of the push notification.
PushNotification
The PushNotification object contains the following fields:
Field | Type | Description | Notes |
type | The type of push data. | Distinguishes between a notification and a message. | |
msgId | string | The message ID. | The identity of the push data. |
title | string | The notification title. | |
content | string | The notification content. | |
ext | Record<string, string | number | boolean> | The extended parameters of the push. | |
notifyId | number | The ID of the notification to be created, specified by the service. | |
open | The operation to perform when the notification is tapped. | ||
uri | string | Specifies the Ability to open by its URI. Used when open is set to Ability. | When open is set to Ability, at least one of the uri and act fields must be specified. |
act | string | Specifies the Ability to open by its action. Used when open is set to Ability. | When open is set to Ability, at least one of the uri and act fields must be specified. |
notificationSlotType | notificationManager.SlotType | The channel type for creating the notification, specified by the service. | Definition of HarmonyOS |
style | number | The style of the notification. | 0: standard style. 3: multi-line text style. |
inboxContent | Array<string> | The list of text for the multi-line text style. Used when style is set to 3. | |
image | string | The URL of the icon on the right side of the notification. |
PushDataType
PushDataType indicates whether the push data is a notification or a message. It is defined as follows:
export enum PushDataType {
Notification = 1,
Message = 2,
}OpenType
OpenType indicates the operation to perform when a user taps a notification. These operations include opening the application or a specified Ability. It is defined as follows:
export enum OpenType {
App = 1,
Ability = 2,
}The onReceiveNotification method requires a boolean return value. A return value of false indicates that the SDK creates the notification. A return value of true indicates that the application creates the notification based on the PushNotification parameters.
If the onReceiveNotification method returns false, the SDK creates and publishes the notification. After the notification is published, the SDK calls the onShowNotification callback method to inform the application that the notification was published successfully. The notification then appears in the notification bar.
If the onReceiveNotification method returns true, the SDK does not create or publish the notification and does not call the onShowNotification method. Return true for scenarios where the application needs to customize the notification.
Customize notifications
To customize a notification, return true in the onReceiveNotification method. The application is then responsible for creating and publishing the notification. You can create and publish the notification as needed based on the PushNotification parameters and the HarmonyOS document Publish Notifications.
If only minor customizations are needed, you can also call the createNotificationRequest method of the IPushHelper in the SDK to quickly create a notificationManager.NotificationRequest object.
The following code shows an example of customizing a notification:
import { aliyunPush, IPushListener, PushError, PushMessage, PushNotification } from '@aliyun/push';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
/**
* Push callback interface implementation for receiving push data
*/
class MyPushListener implements IPushListener {
onReceiveNotification(data: PushNotification): boolean {
// ************* Customize notification begin *************
aliyunPush.getPushHelper().createNotificationRequest(data).then((request) => {
// This example shows how to customize the title by adding "Urgent: " before it.
if (data.style === 3 && request.content.multiLine !== undefined) {
request.content.multiLine.title = "Urgent: " + request.content.multiLine.title;
request.content.multiLine.longTitle = "Urgent: " + request.content.multiLine.longTitle;
} else if (request.content.normal !== undefined) {
request.content.normal.title = "Urgent: " + request.content.normal.title;
}
// Publish the notification.
notificationManager.publish(request).then(() => {
console.debug(`Custom notification published successfully`)
// To unify the logic, you can also actively call the onShowNotification method here.
this.onShowNotification(data);
}).catch((e: BusinessError) => {
console.error(`Failed to publish the custom notification: ${e.code} ${e.message}`)
})
}).catch((e: PushError) => {
console.error(`Failed to create the notification request: ${e.code} ${e.message}`)
})
// ************* Customize notification end *************
// Return true to have the application process the notification.
return true;
}
onShowNotification(data: PushNotification): void {
// Process the notification display event.
}
onReceiveMessage(data: PushMessage): void {
// Process the push message.
}
}
// Other code is omitted.Receive push messages
When the SDK receives a push message, it calls the onReceiveMessage callback method. The PushMessage parameter contains the parameters of the push message.
PushMessage
The PushMessage object contains the following fields:
Field | Type | Description | Notes |
type | The type of push data. | Understand the difference between notifications and messages. | |
msgId | string | The message ID. | The identity of the push data. |
title | string | The message title. | |
content | string | The message content. |
Get push data from a notification
When you send a push notification, you can specify the action that occurs when a user taps the notification. These actions include opening the application's homepage or a custom page in the application.
When the corresponding Ability for the page starts, call the handleClickNotification method to retrieve the push data from the Want parameter.
The following code shows an example:
import { aliyunPush, Channel, PushMessage, PushNotification, PushNotificationHandler } from '@aliyun/push';
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
// ************* Custom push data handler class begin *************
class MyPushNotificationHandler implements PushNotificationHandler {
onClickNotification(data: PushNotification | PushMessage, from: Channel): void {
// Process the push data as needed.
}
noPushData(): void {
// No push data. The interface was not launched by a user tapping a push notification.
}
}
// ************* Custom push data handler class end *************
// The Ability to open when the notification is tapped.
export class TargetAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// ************* Initialize Push begin *************
aliyunPush.init({
appKey: 'Enter the AppKey that you queried in the preparations.',
appSecret: 'Enter the AppSecret that you queried in the preparations.',
context: this.context,
})
// ************* Initialize Push end *************
// ************* Process push data begin *************
aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
// ************* Process push data end *************
}
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// Scenario where the page is already running.
// ************* Process push data begin *************
aliyunPush.handleClickNotification(want, new MyPushNotificationHandler())
// ************* Process push data end *************
}
// Other code is omitted.
}To retrieve push data, the push service must be initialized first. Therefore, in the onCreate method of the Ability, you must call the init method before you call the handleClickNotification method.
If the Ability has already been created, the system does not execute the onCreate method when the user opens the Ability. Instead, the system calls the onNewWant method to pass the new Want parameter. Therefore, you must also call the handleClickNotification method within the onNewWant method to retrieve the push data.
Calling the handleClickNotification method is part of the SDK integration flow. For a complete code example, see Complete SDK integration code example.
Scenario description
Push data is primarily obtained from the parameters of the onClickNotification method in the PushNotificationHandler interface. The parameter values vary based on the scenario. The following table describes these scenarios.
Scenario | data | from | Description |
Push notification through the Alibaba Cloud channel | Channel.Aliyun | A push notification is sent through the Alibaba Cloud channel when the application is online. The notification is created and published by the SDK. | |
Push notification through the vendor channel | Channel.HarmonyOS | A push notification is sent through the vendor channel when the application is offline and a vendor channel is available. The notification is created and published by the HarmonyOS system. | |
Message converted to notification | Channel.HarmonyOS | A push message is sent when the application is offline and a vendor channel is available. The message is allowed to be converted to a notification and sent through the vendor channel. The notification is created and published by the HarmonyOS system. |
The from parameter is defined as follows:
/**
* Push channel
*/
export enum Channel {
/**
* Alibaba Cloud channel
*/
Aliyun,
/**
* HarmonyOS vendor channel
*/
HarmonyOS,
}The application must determine the source of the push data based on the from parameter. Then, it must use the type field of the data object to determine whether the data is a notification or a message. Finally, the application can process the push data as needed.