目录

Managing the Notification Badge

The system provides APIs for setting the notification badge, which is displayed in the upper right corner of the application icon on the home screen to notify the user of the count of unread notifications.

When a new notification arrives, the count on the badge is incremented by 1.

After a notification is read, the count on the badge is decremented by 1. If there is no unread notification, the badge is not displayed.

Available APIs

When the badge count is set to a value less than or equal to 0, the badge is cleared. When the value is greater than 99, the notification badge displays 99+.

How to Develop

  1. Import the NotificationManager module.

    import { notificationManager } from '@kit.NotificationKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    const TAG: string = '[PublishOperation]';
    const DOMAIN_NUMBER: number = 0xFF00;
  2. Increase the count on the badge.

    When publishing a notification, you can carry the related information in the badgeNumber field of NotificationRequest. For details, see Publishing a Text Notification.

    In this example, the setBadgeNumber API is called to add a badge. This API is called after a new notification is published.

    let badgeNumber: number = 9;
    notificationManager.setBadgeNumber(badgeNumber).then(() => {
      hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in setting badge number.`);
    }).catch((err: BusinessError) => {
      hilog.error(DOMAIN_NUMBER, TAG,
        `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);
    });
  3. Decrease the count on the badge.

    After a notification is read, the application needs to call the API to set the number of remaining unread notifications. The badge is then updated.

    let badgeNumber: number = 8;
    notificationManager.setBadgeNumber(badgeNumber).then(() => {
      hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in setting badge number.`);
    }).catch((err: BusinessError) => {
      hilog.error(DOMAIN_NUMBER, TAG,
        `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);
    });

FAQs

setBadgeNumber is an asynchronous API. When setBadgeNumber is used to set badges consecutively, you should not set the value until the previous setting is complete, ensuring that the execution sequence meets the expectation.