DEV Community

HarmonyOS
HarmonyOS

Posted on

How to vibrate user's watch with notification?

Read the original article:How to vibrate user's watch with notification?

Requirement Description

User wants to send notifications with vibrations to the user. It’s especially useful for developers who want to inform users about events such as navigation directives, completed tasks, reminders, or fitness trackers.

Background Knowledge

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

  • Define the required runtime permissions.
  • Request user consent for notifications.
  • Use NotificationKit for customizing the notification behavior.
  • Use ReminderAgentManager to publish background reminders.
  • Implement '@ohos.vibrator' to start vibration

Implementation Steps

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

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

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';
import { vibrator } from '@kit.SensorServiceKit';
Enter fullscreen mode Exit fullscreen mode

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}`);
  });
}
Enter fullscreen mode Exit fullscreen mode

Code Snippet / Configuration

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 sendReminder() {
  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: 'Write your title here',
    content: 'Write your content',
    expiredContent: 'After notification ends, this value is shown',
    notificationId: 100,
    slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
  }
  reminderAgentManager.publishReminder(targetReminderAgent).then((res: number) => {
    // this try catch starts the vibration
    try {
      vibrator.startVibration({
        type: 'time',
        // duration is on you
        duration: 1000,
      }, {
        id: 0,
        usage: 'alarm'
      }, (error: BusinessError) => {
        if (error) {
          // error scenarios
          Logger.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
          return;
        }
        Logger.info('Succeed in starting vibration');
      });
    } catch (err) {
      let e: BusinessError = err as BusinessError;
      Logger.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
    }
    Logger.info('Succeeded in publishing reminder. ');
  }).catch((err: BusinessError) => {
    Logger.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
  })
}
Enter fullscreen mode Exit fullscreen mode

Limitations or Considerations

Before implementing background notifications and vibration, 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.

Related Documents or Links

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

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

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

Written by Hatice Akyel

Top comments (0)