🔔How to send notifications to user while app is running on background?🔔

Read the original article:🔔How to send notifications to user while app is running on background?🔔

Hey there fellow developers!👋 Let’s look at running an app on background and send notifications at the same time. It’s especially useful for developers who want to inform users about events such as completed tasks, reminders, or updates without requiring the app to be open in the foreground.⌚

To enable background notifications in HarmonyOS using ArkTS, developers must:

  • Define the required runtime permissions.
  • Request user consent for notifications.
  • Use ReminderAgentManager to publish background reminders.
  • Use NotificationKit for customizing the notification behavior.
    🚀 Let’s implement our sample notification:

1. Firstly in module.json5 file of the applications these permissions should be added: ohos.permission.KEEP_BACKGROUND_RUNNING, ohos.permission.PUBLISH_AGENT_REMINDER

"requestPermissions":[
      {
        "name" : "ohos.permission.KEEP_BACKGROUND_RUNNING",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"inuse"
        }
      },
      {
        "name" : "ohos.permission.PUBLISH_AGENT_REMINDER",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"inuse"
        }
      }
    ]

2. 📦Necessary kits should be imported.

import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
import { reminderAgentManager } from '@kit.BackgroundTasksKit';

3. Then user should give permission to take notification from the app:

private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
export default async function getPermission(context: common.UIAbilityContext): Promise<void> {
  notificationManager.isNotificationEnabled().then((data: boolean) => {
    hilog.info(DOMAIN_NUMBER, TAG, 'isNotificationEnabled success, data: ' + JSON.stringify(data));
    if (!data) {
      notificationManager.requestEnableNotification(context).then(() => {
        hilog.info(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification success`);
      }).catch((err: BusinessError) => {
        if (1600004 == err.code) {
          hilog.error(DOMAIN_NUMBER, TAG,
            `[ANS] requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
        } else {
          hilog.error(DOMAIN_NUMBER, TAG,
            `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
        }
      });
    }
  }).catch((err: BusinessError) => {
    hilog.error(DOMAIN_NUMBER, TAG, `isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);
  });
}

getPermission method should be called before the sendNotification method.

Taking permission from user looks like this:⏱️

You can customize this method belong to your needs and call it wherever you need. Because it is already running on background even the app is opened or not.

export function sendNotification(title: string, content:string, expired: string) {
  let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = {
    reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER,
    // you can also customize trigger in time second and take it as a parameter
    triggerTimeInSeconds: 10,
    //close button
    actionButton: [
      {
        title: 'close',
        type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
      },
    ],
   // personalize these values belonging to  your app
    wantAgent: {
      pkgName: 'com.example.myapplication',
      abilityName: 'EntryAbility'
    },
    title: this.title,
    content: this.content,
    // after notification disseappears expiredContent value is shown
    expiredContent: this.expired,
    notificationId: 100,
    slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
  }
  reminderAgentManager.publishReminder(targetReminderAgent)
}

⚠️Limitations or Considerations

Before implementing background notifications, make sure you have:
HarmonyOS SDK with ArkTS support.

  • A working ArkTS project.
  • Configured permissions in your module.json5.
  • Always check and request permissions before posting notifications.
  • Keep notifications clear and relevant.
  • Avoid sending too many background notifications, or users may disable them.
  • Don’t rely on background tasks for critical operations unless background execution is guaranteed.

References📘
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/background-task-kit

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/notification-kit

https://forums.developer.huawei.com/forumPortal/en/topic/0203190032965492052?fid=0102647487706140266

Written by Hatice Akyel

Similar Posts