HarmonyOS基础技术赋能之通知功能实现 原创 精华
软通张二龙
发布于 2021-8-30 11:37
浏览
16收藏
引言
HarmonyOS通过ANS(Advanced Notification Service,即通知增强服务)系统服务来为应用程序提供发布通知的能力。通知提供应用的即时消息或通信消息,用户可以直接删除或点击通知触发进一步的操作。
功能介绍
HarmonyOS提供了通知功能,即在一个应用的UI界面之外显示的消息,主要用来提醒用户有来自该应用中的信息。当应用向系统发出通知时,它将先以图标的形式显示在通知栏中,用户可以下拉通知栏查看通知的详细信息。常见的使用场景:
1) 显示接收到短消息、即时消息等。
2) 显示应用的推送消息,如广告、版本更新等。
3) 显示当前正在进行的事件,如播放音乐、导航、下载等。
指南
通知的开发指导分为创建NotificationSlot、发布通知和取消通知等开发场景。
1.创建NotificationSlot
1.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.");
}
2. 发布通知
1) 构建NotificationRequest对象
request = new NotificationRequest(notificationId);
request.setSlotId(slot.getId());
2) 调用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);//设置用户点击通知后自动消失
3)调用publishNotification()发布通知。
try {
NotificationHelper.publishNotification(request);
} catch (RemoteException ex) {
HiLog.warn(LABEL, "publishNotification occur exception.");
}
3. 取消通知
1)
调用cancelNotification()取消指定的单条通知。
try {
NotificationHelper.cancelNotification(notificationId);
} catch (RemoteException ex) {
HiLog.error(LABEL, "Exception occurred during cancelNotification invocation.");
}
2)
调用cancelAllNotifications()取消所有通知。
try {
NotificationHelper.cancelAllNotifications();
} catch (RemoteException ex) {
HiLog.error(LABEL, "Exception occurred during cancelAllNotifications invocation.");
}
4. 通过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<Intent> intentList = new ArrayList<>();
intentList.add(intent1);
// 定义请求码
int requestCode = 200;
// 设置flags
List<IntentAgentConstant.Flags> 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);
实现效果图:
附上源码:
1. 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<Intent> intentList = new ArrayList<>();
intentList.add(intent1);
// 定义请求码
int requestCode = 200;
// 设置flags
List<IntentAgentConstant.Flags> 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);
}
}
2. 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;
}
}
}
3. 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"/>
</DirectionalLayout>
4. 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"/>
</shape>
更多原创内容请关注:软通动力HarmonyOS学院
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
赞
19
收藏 16
回复
相关推荐
张老师基础技能讲解写的非常详细
感谢张老师分享
感谢张老师分享
感谢张老师分享
感谢张老师分享
请问这个消息可以使用在手表里面吗?张老师
感谢老师的分享