DEV Community

Cover image for Introduction and Practice of HarmonyOS Next User Notification Service Notification Kit
kouwei qing
kouwei qing

Posted on

Introduction and Practice of HarmonyOS Next User Notification Service Notification Kit

Introduction and Practical Guide to HarmonyOS Next User Notification Service (Notification Kit)

1. Overview of Notification Kit

Notification Kit provides developers with a local notification delivery channel, enabling apps to push notifications directly to users on the client side. These notifications—triggered by app events—can include ringtones, vibrations, banners, lock screen alerts, status bar notifications, and more, similar to Android’s notification system.

Example: Status Bar Icon Display

Users can swipe down the status bar to access the notification drawer for details and actions.

Reminder-Style Notifications:

HarmonyOS offers equivalent capabilities through Notification Kit.

2. Differences Between Notification Kit, Call Kit, and Push Kit

  • Notification Kit: Developers manually invoke APIs to create and define notifications.
  • Push Kit: Huawei’s cloud-to-device messaging platform. Integrating Push Kit enables real-time app notifications, enhancing user engagement. Push Kit runs as a system daemon, launching the app process when notifications are tapped. Display scenarios include the notification center, lock screen, banners, and badge icons.
  • Call Kit: Manages in-app call features (e.g., one-tap answer, banners, mute). When the app is in the background, Push Kit must first wake the app process before Call Kit can handle calls.

Relationship Diagram:

Key Workflow:

  1. Push Kit receives a notification and wakes the app.
  2. The app uses Notification Kit to display the alert.
  3. Tapping the notification triggers Call Kit for call handling.

3. Notification Kit Features and APIs

Core Workflow:

  1. Request notification permissions.
  2. Publish notifications via the service.
  3. Display notifications in the system tray.
Requesting Permissions

Apps must obtain user consent before sending notifications. Use requestEnableNotification() to prompt the user; subsequent calls skip the prompt if already granted.

API Reference:

| API | Description |

|---------|----------------|

| isNotificationEnabled(): Promise<boolean> | Checks if notifications are enabled. |

| requestEnableNotification(context: UIAbilityContext): Promise<void> | Requests permission (prompts user on first call). |

Code Example:

import { notificationManager } from '@kit.NotificationKit';
// ... (other imports)
const TAG: string = '[PublishOperation]';

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
notificationManager.isNotificationEnabled().then((data: boolean) => {
  if (!data) {
    notificationManager.requestEnableNotification(context).then(() => {
      hilog.info(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification success`);
    }).catch((err: BusinessError) => {
      if (err.code === 1600004) { // Permission denied
        hilog.error(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification refused, code: ${err.code}`);
      }
    });
  }
}).catch((err: BusinessError) => {
  hilog.error(DOMAIN_NUMBER, TAG, `isNotificationEnabled failed: ${err.message}`);
});
Enter fullscreen mode Exit fullscreen mode
Publishing Notifications

Common notification types:

Type Style Description
Text Max 3 lines (truncated with "...").
Multi-line Text Truncates long lines.
Badge Badge Numeric counter in top-right.
Progress Bar Progress Shows download/progress status.

Example: Text Notification

let request: notificationManager.NotificationRequest = {
  id: 1,
  content: {
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: { title: 'test_title', text: 'test_text' }
  }
};
notificationManager.publish(request, (err) => { /* Handle errors */ });
Enter fullscreen mode Exit fullscreen mode

Progress Bar Template:

// Check template support
notificationManager.isSupportTemplate('downloadTemplate').then((supported) => {
  if (supported) {
    let request: notificationManager.NotificationRequest = {
      id: 5,
      content: { /* ... */ },
      template: { name: 'downloadTemplate', data: { progressValue: 45 } }
    };
    notificationManager.publish(request, (err) => { /* ... */ });
  }
});
Enter fullscreen mode Exit fullscreen mode

Canceling Notifications:

notificationManager.cancel(1, (err) => { /* ... */ }); // Cancels notification with ID=1
Enter fullscreen mode Exit fullscreen mode

4. Use Cases

  • Foreground/Background:
    • Foreground: Directly publish notifications.
    • Background: Requires Push Kit for cloud-delivered alerts.
  • Scenarios: Syncing upload progress, payment alerts, fitness tracking.

System Limitations:

  • Max 24 notifications retained in the system tray.
  • 200KB size limit per notification.
  • Rate limits: 10 new/20 updates per second (per app); 15/30 for all third-party apps combined.

5. IM Scenario Practical Guide

Basic Setup:

  • Push Kit: Handles background notifications. Unlike Android, HarmonyOS cannot "keep apps alive," so Push Kit is essential.
  • Foreground Handling: Use foregroundShow: false in REST API to suppress notifications when the app is active.

Example Payload:

{
  "payload": {
    "notification": { "foregroundShow": false },
    "target": { "token": ["IQAAAA**********4Tw"] }
  }
}
Enter fullscreen mode Exit fullscreen mode

Custom Notifications:

Parse Push Kit messages and create text notifications dynamically:

let request: notificationManager.NotificationRequest = {
  id: 1,
  content: { normal: { title: notification.title, text: notification.text } }
};
notificationManager.publish(request, (err) => { /* ... */ });
Enter fullscreen mode Exit fullscreen mode

Badge Management:

// Increment badge count
notificationManager.setBadgeNumber(9, (err) => { /* ... */ });

// Decrement after viewing a notification
notificationManager.setBadgeNumber(8, (err) => { /* ... */ });
Enter fullscreen mode Exit fullscreen mode

Notification Channels:

Define channels for different message types (e.g., chats vs. marketing):

notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION, (err) => { /* ... */ });
Enter fullscreen mode Exit fullscreen mode

Custom Ringtones:

Place audio files in resources/rawfile/ and reference them via the sound field (requires app eligibility).

Click Actions:

Use WantAgent to deep-link to specific app pages:

let wantAgentInfo: wantAgent.WantAgentInfo = {
  wants: [{ bundleName: 'com.samples.notification', abilityName: 'SecondAbility' }],
  actionType: wantAgent.OperationType.START_ABILITY
};
Enter fullscreen mode Exit fullscreen mode

6. Summary

Notification Kit empowers developers to create local notifications with rich features (text, progress bars, badges, etc.), complementing Push Kit (cloud messaging) and Call Kit (call management). Key steps include:

  1. Requesting permissions.
  2. Building notification templates.
  3. Publishing/canceling notifications.

Best Practices:

  • Respect system limits (24 notifications, 200KB size).
  • Use Push Kit for background delivery.
  • Customize channels/ringtones for specific scenarios.

Ideal for IM, fitness apps, and other time-sensitive notifications.

Top comments (0)