Best Practices for PushKit in Assisting IM Message Notification Scenarios



This content originally appeared on DEV Community and was authored by kouwei qing

HarmonyOS Next IM Combat: Best Practices for PushKit in Assisting IM Message Notification Scenarios

Background Introduction

In IM development, besides sending and receiving messages, message reminders constitute a crucial component. In the traditional Android era, with no access to GMS in China, developers explored various keep-alive solutions to prevent apps from being killed in the background and enable continuous message reception. As Android systems evolved, these keep-alive methods were gradually blocked by the system, while manufacturers introduced system Push services, allowing apps to receive messages even when closed.

In the HarmonyOS Next system, similar to iOS, apps are not allowed to stay alive indefinitely. However, the system provides a PushKit notification service, enabling apps to apply for integration with PushKit to implement message pushing.

Introduction to HarmonyOS Next System Push Status

PushKit (Push Service) is a message pushing platform provided by Huawei, establishing a message push channel from the cloud to the terminal. All HarmonyOS apps can integrate PushKit to push real-time messages, making messages visible, building good user relationships, and enhancing user awareness and activity. Display scenarios mainly include the notification center, lock screen, banners, desktop icon badges, and notification icons.

text

PushKit supports not only notification messages but also authorized subscription messages, notification extension messages, card refresh messages, background messages, live window messages, in-app call messages, etc.

PushKit offers three key advantages:

  • Stable message sending channel: PushKit provides a system-level long connection, enabling real-time message pushing even when the app process is inactive.
  • Rich message presentation styles: Supports multiple display modes such as text, notification large icons, multi-line text, and badge styles to meet diverse and personalized message sending needs.
  • Flexible scenario-based messages: Developers can flexibly integrate scenario-based messages according to actual needs. For example, implement audio/video calls via in-app call messages, voice broadcasting via notification extension messages, and configuration updates via background messages.

The overall usage process is as follows:

text

  1. The app calls PushKit to obtain a Push Token.
  2. After successfully acquiring the Token, the app should promptly report the Token and other information to the app server.
  3. The app server sends a push message request to Huawei’s PushKit server (Push Cloud). The app’s notification switch is closed by default; request notification authorization before sending the request.
  4. The PushKit server delivers the message to PushKit.
  5. PushKit processes the message.

Despite PushKit’s powerful capabilities and effects, a challenge arises in IM scenarios: when chatting with a specific user, new messages from that user should not trigger notifications, while notifications should function normally otherwise.

In iOS, PushKit allows apps to intervene in notification display when active. When in the foreground, the app can determine if it is on the chat page and if the message is from the corresponding user, preventing continuous notifications during active chat. HarmonyOS does not provide this capability directly, but it offers a way to handle notification messages when the app is in the foreground. The server can call the REST API to push notification messages with a foregroundShow field set to false in the message body (default is true, meaning display in both foreground and background), which prevents notification display when the app is in the foreground:

// Request Body
{
  "payload": {
    "notification": {
      "category": "MARKETING",
      "title": "普通通知标题",
      "body": "普通通知内容",
      "profileId": "111***222",
      "clickAction": {
        "actionType": 0
      },
      "foregroundShow": false  // Set to false to disable notification display when the app is in the foreground
    }
  },
  "target": {
    "token": ["IQAAAA**********4Tw"]
  }
}

In the client project’s src/main/module.json5 file, configure the actions attribute in the skills tag of the corresponding Ability (e.g., PushMessageAbility) as action.ohos.push.listener (only one Ability in the project should define this action):

{
  "name": "PushMessageAbility",
  "srcEntry": "./ets/abilities/PushMessageAbility.ets",
  "launchType": "singleton",
  "startWindowIcon": "$media:startIcon",
  "startWindowBackground": "$color:start_window_background",
  "exported": false,
  "skills": [
    {
      "actions": [
        "action.ohos.push.listener"
      ]
    }
  ]
}

In the existing UIAbility class of the client project (e.g., PushMessageAbility), use the receiveMessage() method in onCreate() with PushType as “DEFAULT” to receive notification messages when the app is in the foreground. Sample code:

import { UIAbility } from '@kit.AbilityKit';
import { pushService } from '@kit.PushKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';


/**
 * Example of PushMessageAbility for receiving notification messages when the app is in the foreground
 */
export default class PushMessageAbility extends UIAbility {
  onCreate(): void {
    try {
      // The parameter in receiveMessage is fixed as DEFAULT
      pushService.receiveMessage('DEFAULT', this, (payload) => {
        try {
          // Get data passed from the server
          const data: string = payload.data;
          // TODO: Custom business processing
          hilog.info(0x0000, 'testTag', 'Succeeded in getting notification,data=%{public}s',
            JSON.stringify(JSON.parse(data)?.notification));
        } catch (e) {
          let errRes: BusinessError = e as BusinessError;
          hilog.error(0x0000, 'testTag', 'Failed to process data: %{public}d %{public}s',
            errRes.code, errRes.message);
        }
      });
    } catch (err) {
      let e: BusinessError = err as BusinessError;
      hilog.error(0x0000, 'testTag', 'Failed to get message: %{public}d %{public}s', e.code,
        e.message);
    }
  }
}

WeChat currently employs this solution: notifications are displayed normally when the app is in the background, while only a subtle vibration is triggered in the foreground. However, in scenarios like official account pages, mini-programs, or video channels, message awareness is insufficient, increasing the risk of missed messages.

Note: Ensure correct configuration of action.ohos.push.listener. During development, multi-channel packages with this action only configured in the default module.json5 may fail to receive foreground notifications.

Solution Introduction

Completely disabling foreground notifications via PushKit risks missed messages, yielding suboptimal results. HarmonyOS Next provides Notification Kit (User Notification Service), which offers a local notification publishing channel for developers. Notification Kit allows apps to push notifications directly to users locally when running in the foreground. When the app moves to the background, the local notification channel closes, and PushKit is used for cloud-side offline notification publishing. Local notification capabilities can be applied in various scenarios, such as syncing upload/download progress, publishing instant customer service payment notifications, and updating step counts.

Notification Kit supports the following key capabilities:

  • Publish text, progress bar, and other notification types.
  • Carry or update app notification badge counts.
  • Cancel specific or all previously published notifications.
  • Query the list of published notifications.
  • Query the app’s own notification switch status.
  • The app’s notification capability is off by default; developers can trigger an authorization dialog to request user permission.

The overall usage process is as follows:

text
Here is a simple example of publishing a text notification:

let notificationRequest: notificationManager.NotificationRequest = {
  id: 1,
  content: {
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic text notification type
    normal: {
      title: 'test_title',
      text: 'test_text',
      additionalText: 'test_additionalText',
    }
  }
};
notificationManager.publish(notificationRequest, (err: BusinessError) => {
  if (err) {
    hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
    return;
  }
  hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');
});

For detailed explanations of NotificationRequest, refer to: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-notification-notificationrequest#notificationrequest

The sound field is also supported, but the specified file must be placed in the resources/rawfile directory, supporting formats like m4a, aac, mp3, ogg, wav, flac, and amr. This field only takes effect after the app applies for and obtains the notification custom ringtone privilege. Currently, this field works in PushKit but not in Notification Kit, an issue under investigation.

The notification ID defaults to 0. When the same ID exists, the notification content is updated. This allows updating effects and list displays using conversation IDs or message IDs.

The wantAgent field can specify the notification click jump logic. Notifications can be canceled via notificationManager.cancel, either for a specific ID or all notifications.

Summary

In HarmonyOS Next’s IM message notification scenarios, PushKit provides stable cloud-side pushing capabilities, but by default, it cannot distinguish between foreground and background states, causing frequent notifications on chat pages that degrade user experience. While foregroundShow: false can disable foreground notifications, it weakens message awareness. By combining PushKit with Notification Kit’s local notification capabilities, a more refined message reminder strategy is achieved: background messages are pushed via PushKit to ensure delivery, while foreground messages are triggered on demand via Notification Kit (e.g., for non-chat page reminders), balancing message reach and user experience. This hybrid solution leverages the reliability of system-level pushing and implements scenario-based notification control through client-side logic, representing the best practice for IM app message notifications on HarmonyOS Next. Developers must pay attention to permission configuration, lifecycle management, and multi-module collaboration (e.g., ensuring correct declaration of action.ohos.push.listener) to fully leverage the advantages of dual-channel notifications.


This content originally appeared on DEV Community and was authored by kouwei qing