DEV Community

HarmonyOS
HarmonyOS

Posted on

How to begin working with Notification Kit?

Read the original article:How to begin working with Notification Kit?

Requirement Description

This implementation aims to publish a basic text notification on HarmonyOS using the Notification Kit. The notification informs the user when a match ends, prompting them to check the details. The process includes requesting notification permissions dynamically and publishing the notification if permissions are granted.

Background Knowledge

Before working with the Notification Kit, the following modules and concepts should be understood:

  • @kit.NotificationKit: Provides APIs to publish, cancel, and manage notifications.
  • @kit.BasicServicesKit → BusinessError: Used to handle errors returned from system service calls.
  • @kit.AbilityKit → common.UIAbilityContext: Represents the context used for UI-related operations.
  • @kit.PerformanceAnalysisKit → hilog: Used for logging information, especially for debugging or performance monitoring.

Notification permission must be explicitly requested at runtime for newer HarmonyOS versions to ensure proper functioning.

Implementation Steps / Code Snippets

  • Import Required Modules Import the required kits to access notification APIs, logging, and context management:
  import { notificationManager } from '@kit.NotificationKit';
  import { BusinessError } from '@kit.BasicServicesKit';
  import { common } from '@kit.AbilityKit';
  import { hilog } from '@kit.PerformanceAnalysisKit';
Enter fullscreen mode Exit fullscreen mode
  • Define Constants Set up a logging tag and domain for consistent error reporting:
  const TAG: string = '[PublishOperation]';
  const DOMAIN_NUMBER: number = 0xFF00;
Enter fullscreen mode Exit fullscreen mode
  • Request Notification Permission Create a function to prompt the user to allow notifications:
  export function openNotificationPermission(context: common.UIAbilityContext) {
    setTimeout(() => {
      notificationManager.requestEnableNotification(context)
        .then(() => { /* Permission granted */ })
        .catch((err: BusinessError) => { /* Handle error */ });
    }, 1000);
  }
Enter fullscreen mode Exit fullscreen mode
  • Publish Notification Send a basic notification:
  export function sendNotification() {
    let context = getContext() as common.UIAbilityContext;
    openNotificationPermission(context);

    let notificationRequest: notificationManager.NotificationRequest = {
      id: 1,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: 'Match is over',
          text: 'Please check details',
          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.');
    });
  }
Enter fullscreen mode Exit fullscreen mode

Integrate with LifeCycle: Send Periodic Notifications

Inside onWindowStageCreate, an interval is set to trigger the notification logic every 30 seconds:

  onWindowStageCreate(windowStage: window.WindowStage): void {
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    if (intervalId !== undefined) {
      clearInterval(intervalId);
    }

    intervalId = setInterval(() => {
      seconds++;
      hilog.info(0x0000, TAG, 'Sending notification from Service Ability');
      SecondsService.getInstance().second = seconds;

      if (seconds >= 30) {
        sendNotification();
        seconds = 0;
      }
    }, 1000);

    windowStage.loadContent('pages/Index', (err) => {
      if (err.name) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    });
  }
Enter fullscreen mode Exit fullscreen mode

Test Results

This example demonstrates how to combine notification management with UI lifecycle events to create a time-driven alert mechanism in a HarmonyOS application. By leveraging setInterval within onWindowStageCreate, the app continuously tracks time and triggers a notification every 30 seconds.

Always make sure that the notification permission is requested at the appropriate time and handled gracefully, as it is a crucial part of the user experience in HarmonyOS. For more advanced scenarios, developers can explore other notification types like media, multi-line, and action buttons, and also integrate user interactions with the notification service.

Written by Egemen Ayhan

Top comments (0)