如何在鸿蒙系统中使用系统通知?

阅读 1.2k
avatarAI BotBETA

在鸿蒙系统中使用系统通知,主要需使用Notification API及相关服务。以下是如何为应用提供通知功能的详细步骤:

一、引入必要的模块

确保项目中已引入必要的模块,通过SDK和API直接支持Notification功能。

二、创建通知

使用Notification类或其子类创建通知,并设置通知属性,如标题、内容、图标等。例如:

import { notificationManager } from '@kit.NotificationKit';

let notificationRequest: notificationManager.NotificationRequest = {
    id: 1, // 通知ID
    content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
            title: '通知内容标题',
            text: '通知内容详情'
        }
    }
};

三、注册通知渠道(如需要)

若应用目标版本要求类似Android的通知渠道机制,则需先注册通知渠道。

四、发送通知

使用NotificationManager或类似服务发送通知。例如:

notificationManager.publish(notificationRequest).then(() => {
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed, message is ${err}`);
});

五、处理通知交互

若通知可交互(如包含按钮或可展开的内容),还需实现相应的回调或广播接收器处理交互。

六、使用Push Kit推送服务(可选)

鸿蒙系统提供了Push Kit推送服务,可建立从云端到终端的消息推送通道,实现实时推送消息。开发者需集成Push Kit,并申请Push Token,以便根据Token推送消息。

七、测试和调试

完成通知功能的集成后,需进行充分测试以确保通知正常显示和交互。

八、通知管理

  • 更新通知:使用相同的通知ID再次调用notificationManager.publish来更新已发布的通知。
  • 取消通知:通过通知ID或通知标签取消已发布的通知,或使用notificationManager.cancelAll()取消所有已发布的通知。
  • 通知通道:使用不同的通知通道(slotType)来让通知有不同的表现形式,如社交类型的通知可以横幅显示并有提示音,而一般的通知则不会横幅显示。
notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => {
    console.info("addSlot success");
}).catch((err: Base.BusinessError) => {
    console.error(`addSlot fail: ${JSON.stringify(err)}`);
});

九、引导用户设置通知权限

如果应用首次被拒绝了消息通知权限,可以引导用户拉起系统设置应用来设置允许通知。例如:

let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: "systemui_notification_settings",
    parameters: {
        pushParams: {
            bundleName: context.abilityInfo.bundleName
        }
    }
};
context.startAbility(want);

并在打开页面时获取通知管理中按钮状态,使用Notification.requestEnableNotification()请求发送通知的许可。

通过以上步骤,你可以在鸿蒙系统中为应用提供丰富的通知功能,提升用户体验。

2 个回答
  1. 使用 Notification API 创建通知。
  2. 配置权限:ohos.permission.NOTIFICATION.
import notification from '@ohos.notification';

notification.publish({
  content: 'This is a system notification',
  title: 'Notification Title',
});

鸿蒙系统(HarmonyOS)的通知系统与Android系统在许多方面相似,但也有一些特定的差异。以下是在鸿蒙系统中使用系统通知的步骤:

  1. 获取权限
    首先,确保你的应用有发送通知的权限。在config.json文件中添加以下权限:
{
  "module": {
    "reqPermissions": [
      {
        "name": "ohos.permission.NOTIFICATION_CONTROLLER"
      }
    ]
  }
}
  1. 创建通知渠道(HarmonyOS 3.0及以上版本需要)

    if (ohos.systemversion.Build.VERSION.SDK_INT >= ohos.systemversion.Build.VERSION_CODES.S) {
     NotificationHelper notificationHelper = new NotificationHelper(context);
     NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationSlotType.OTHER_TYPES);
     notificationHelper.createNotificationChannel(channel);
    }
  2. 创建通知
    在鸿蒙系统中,你需要创建一个NotificationRequest对象来定义通知的内容和行为。
NotificationRequest request = new NotificationRequest.Builder()
    .setContentTitle("通知标题")
    .setContentText("通知内容")
    .setSmallIcon(ResourceTable.Media_ic_notification)
    .setAutoDeletedTime(10000) // 设置通知自动删除时间,单位为毫秒
    .setSlotType(NotificationSlotType.OTHER_TYPES)
    .build();
  1. 显示通知
    创建NotificationHelper实例,并使用它来发送通知。

    
    NotificationHelper notificationHelper = new NotificationHelper(context);
    notificationHelper.notify(100, request);
  2. 设置点击通知后的行为
    你可以设置一个Intent来指定用户点击通知后应该执行的操作。
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
    .withDeviceId("")
    .withBundleName("com.example.app")
    .withAbilityName("com.example.app.MainAbility")
    .build();
intent.setOperation(operation);

// 将Intent转换为PendingIntent
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);

NotificationRequest.Builder builder = new NotificationRequest.Builder()
    .setContentIntent(pendingIntent)
    // ... 其他设置
    .build();
  1. 处理通知的点击事件
    在你的Ability中重写onStart方法,以处理通知点击事件。

    
    @Override
    public void onStart(Intent intent) {
     super.onStart(intent);
     if (intent != null) {
         String action = intent.getAction();
         if (action != null && action.equals("action.notification.click")) {
             // 处理通知点击事件
         }
     }
    }
    

    本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题