暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

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

鸿蒙技术社区 2021-08-31
1976

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<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);


实现效果图:

附上源码:


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);
  }
}


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"/>

</DirectionalLayout>


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>


👇点击关注鸿蒙技术社区👇

了解鸿蒙一手资讯


“阅读原文”了解更多

文章转载自鸿蒙技术社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论