鸿蒙OS通知功能,轻松实现!

我是NO.1 2021-08-31 13:39:07 3982

HarmonyOS 通过 ANS(Advanced Notification Service,即通知增强服务)系统服务来为应用程序提供发布通知的能力。

通知提供应用的即时消息或通信消息,用户可以直接删除或点击通知触发进一步的操作。

功能介绍

HarmonyOS 提供了通知功能,即在一个应用的 UI 界面之外显示的消息,主要用来提醒用户有来自该应用中的信息。

当应用向系统发出通知时,它将先以图标的形式显示在通知栏中,用户可以下拉通知栏查看通知的详细信息。

常见的使用场景:

显示接收到短消息、即时消息等。

显示应用的推送消息,如广告、版本更新等。

显示当前正在进行的事件,如播放音乐、导航、下载等。

开发指南

通知的开发指导分为创建 NotificationSlot、发布通知和取消通知等开发场景。

①创建 NotificationSlot

代码如下:
NotificationSlot slot = new NotificationSlot("slot_001", "slot_default", NotificationSlot.LEVEL_MIN); // 创建notificationSlot对象
slot.setLevel(LEVEL_HIGH);//设置通知优先级
slot.setDescription("NotificationSlotDescription");
slot.setEnableVibration(true); // 设置振动提醒
slot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);//设置锁屏模式
slot.setEnableLight(true); // 设置开启呼吸灯提醒
slot.setLedLightColor(Color.RED.getValue());// 设置呼吸灯的提醒颜色
try {
NotificationHelper.addNotificationSlot(slot);
} catch (RemoteException ex) {
HiLog.warn(LABEL, "addNotificationSlot occur exception.");
}

②发布通知

构建 NotificationRequest 对象:

request = new NotificationRequest(notificationId);
request.setSlotId(slot.getId());

调用 setContent() 设置通知的内容:

NotificationRequest.NotificationLongTextContent content = new NotificationRequest.NotificationLongTextContent();
content.setTitle(title)
.setText(messageContent);
NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(
content);
request.setGroupValue("group information");
request.setContent(notificationContent); // 设置通知的内容
request.setTapDismissed(!tapDismissed);//设置用户点击通知后自动消失

调用 publishNotification() 发布通知:

try {
NotificationHelper.publishNotification(request);
} catch (RemoteException ex) {
HiLog.warn(LABEL, "publishNotification occur exception.");
}

③取消通知

如下:

调用cancelNotification()取消指定的单条通知。
try {
NotificationHelper.cancelNotification(notificationId);
} catch (RemoteException ex) {
HiLog.error(LABEL, "Exception occurred during cancelNotification invocation.");
}

调用cancelAllNotifications()取消所有通知。
try {
NotificationHelper.cancelAllNotifications();
} catch (RemoteException ex) {
HiLog.error(LABEL, "Exception occurred during cancelAllNotifications invocation.");
}

④通过 IntentAgent 触发通知的跳转

代码如下:

//点击通知,跳转至指定的Ability
Intent intent1 = new Intent();
// 指定要启动的Ability的BundleName和AbilityName字段
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.example.myapplication")
.withAbilityName("com.example.myapplication.SecondAbility")
.build();
// 将Operation对象设置到Intent中
intent1.setOperation(operation);
List intentList = new ArrayList<>();
intentList.add(intent1);
// 定义请求码
int requestCode = 200;
// 设置flags
List flags = new ArrayList<>();
flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
// 指定启动一个有页面的Ability
IntentAgentInfo paramsInfo = new IntentAgentInfo(requestCode,
IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
// 获取IntentAgent实例
IntentAgent agent = IntentAgentHelper.getIntentAgent(context, paramsInfo);
//5.设置通知的IntentAgent
request.setIntentAgent(agent);

实现效果图:

附上源码:

NotificationUtils:

public class NotificationUtils {

private static final int LEVEL_HIGH = 4;
private static NotificationRequest request;
private static final int MY_MODULE = 0x00201;
private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, MY_MODULE, "MY_TAG");
private static final boolean tapDismissed = false;

//3.调用publishNotification()发送通知
public static void publishNotification() {
try {
NotificationHelper.publishNotification(request);
} catch (RemoteException ex) {
HiLog.warn(LABEL, "publishNotification occur exception.");
}
}

public static void initNotificationSlot(Context context, int notificationId, String title,
String messageContent) {
//1.创建NotificationSlot
NotificationSlot slot = new NotificationSlot("slot_001", "slot_default", NotificationSlot.LEVEL_MIN); // 创建notificationSlot对象
slot.setLevel(LEVEL_HIGH);//设置通知优先级
slot.setDescription("NotificationSlotDescription");
slot.setEnableVibration(true); // 设置振动提醒
slot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);//设置锁屏模式
slot.setEnableLight(true); // 设置开启呼吸灯提醒
slot.setLedLightColor(Color.RED.getValue());// 设置呼吸灯的提醒颜色
try {
NotificationHelper.addNotificationSlot(slot);
} catch (RemoteException ex) {
HiLog.warn(LABEL, "addNotificationSlot occur exception.");
}
request = new NotificationRequest(notificationId);
request.setSlotId(slot.getId());
NotificationRequest.NotificationLongTextContent content = new NotificationRequest.NotificationLongTextContent();
content.setTitle(title)
.setText(messageContent);
NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(
content);
request.setGroupValue("group information");
request.setContent(notificationContent); // 设置通知的内容
request.setTapDismissed(!tapDismissed);//设置用户点击通知后自动消失
//4.返回应用,首先获取IntentAgent
Intent intent1 = new Intent();
// 指定要启动的Ability的BundleName和AbilityName字段
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.example.myapplication")
.withAbilityName("com.example.myapplication.SecondAbility")
.build();
// 将Operation对象设置到Intent中
intent1.setOperation(operation);
List intentList = new ArrayList<>();
intentList.add(intent1);
// 定义请求码
int requestCode = 200;
// 设置flags
List flags = new ArrayList<>();
flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
// 指定启动一个有页面的Ability
IntentAgentInfo paramsInfo = new IntentAgentInfo(requestCode,
IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
// 获取IntentAgent实例
IntentAgent agent = IntentAgentHelper.getIntentAgent(context, paramsInfo);
//5.设置通知的IntentAgent
request.setIntentAgent(agent);
}
}

MainAbilitySlice:

public class MainAbilitySlice extends AbilitySlice implements ClickedListener {

@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//通知
Text notification = (Text) findComponentById(ResourceTable.Id_text_notification);
notification.setClickedListener(this);
//通知标题
String title ="测试通知";
//通知内容文本
String content="通知的内容已经到了!";
NotificationUtils.initNotificationSlot(this,1,title,content);
}

@Override
public void onActive() {
super.onActive();
}

@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}

@Override
public void onClick(Component component) {
switch (component.getId()){
case ResourceTable.Id_text_notification:
NotificationUtils.publishNotification();
break;
}
}
}

ability_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:width="match_parent">
<Text
ohos:id="$+id:text_notification"
ohos:width="match_parent"
ohos:height="match_content"
ohos:text_size="25fp"
ohos:top_margin="300vp"
ohos:left_margin="15vp"
ohos:right_margin="15vp"
ohos:background_element="$graphic:background_text"
ohos:text="通知"
ohos:text_weight="1000"
ohos:text_alignment="horizontal_center"/>

background_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<corners
ohos:radius="20"/>
<solid
ohos:color="#a5b3a9"/>

来源:鸿蒙技术社区

声明:本文内容由易百纳平台入驻作者撰写,文章观点仅代表作者本人,不代表易百纳立场。如有内容侵权或者其他问题,请联系本站进行删除。
红包 93 收藏 评论 打赏
评论
0个
内容存在敏感词
手气红包
    易百纳技术社区暂无数据
相关专栏
置顶时间设置
结束时间
删除原因
  • 广告/SPAM
  • 恶意灌水
  • 违规内容
  • 文不对题
  • 重复发帖
打赏作者
易百纳技术社区
我是NO.1
您的支持将鼓励我继续创作!
打赏金额:
¥1易百纳技术社区
¥5易百纳技术社区
¥10易百纳技术社区
¥50易百纳技术社区
¥100易百纳技术社区
支付方式:
微信支付
支付宝支付
易百纳技术社区微信支付
易百纳技术社区
打赏成功!

感谢您的打赏,如若您也想被打赏,可前往 发表专栏 哦~

举报反馈

举报类型

  • 内容涉黄/赌/毒
  • 内容侵权/抄袭
  • 政治相关
  • 涉嫌广告
  • 侮辱谩骂
  • 其他

详细说明

审核成功

发布时间设置
发布时间:
是否关联周任务-专栏模块

审核失败

失败原因
备注
拼手气红包 红包规则
祝福语
恭喜发财,大吉大利!
红包金额
红包最小金额不能低于5元
红包数量
红包数量范围10~50个
余额支付
当前余额:
可前往问答、专栏板块获取收益 去获取
取 消 确 定

小包子的红包

恭喜发财,大吉大利

已领取20/40,共1.6元 红包规则

    易百纳技术社区