HarmonyOS Sample 之 Notification 通知功能 原创 精华

Buty9147
发布于 2021-8-10 15:52
浏览
3收藏

@toc

Notification 通知功能

介绍

通知功能,即在一个应用的UI界面之外显示的消息,主要用来提醒用户有来自该应用中的信息。本示例演示了如何发布通知和取消通知,还有如何发布一个带有回复功能的通知。

效果展示

HarmonyOS Sample 之 Notification 通知功能-鸿蒙开发者社区

搭建环境

安装DevEco Studio,详情请参考DevEco Studio下载
设置DevEco Studio开发环境,DevEco Studio开发环境需要依赖于网络环境,需要连接上网络才能确保工具的正常使用,可以根据如下两种情况来配置开发环境:

如果可以直接访问Internet,只需进行下载HarmonyOS SDK操作。
如果网络不能直接访问Internet,需要通过代理服务器才可以访问,请参考配置开发环境
下载源码,导入项目。

实现步骤

1.订阅事件

定义通知事件订阅者

/**
 * 定义通知事件订阅者,处理接收到的消息
 */
static class NotificationEventSubscriber extends CommonEventSubscriber {
    //
    private final AbilitySlice slice;

    /**
     * Constructor
     *
     * @param subscribeInfo subscribe information
     * @param slice         slice who own the subscriber
     */
    public NotificationEventSubscriber(CommonEventSubscribeInfo subscribeInfo, AbilitySlice slice) {
        super(subscribeInfo);
        this.slice = slice;
    }

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        Intent intent = commonEventData.getIntent();
        if (intent == null) {
            return;
        }
        //
        if (Const.NOTIFICATION_ACTION.equals(intent.getAction())) {

            PacMap pacMap = NotificationUserInput.getInputsFromIntent(intent);

            if (pacMap == null) {
                return;
            }
            //
            String inputText = pacMap.getString(Const.NOTIFICATION_INPUT_KEY);
            //
            slice.getUITaskDispatcher().asyncDispatch(() -> {

                //
                Text replyText = (Text) slice.findComponentById(ResourceTable.Id_notify2_reply);
                replyText.setText(inputText);
            });
        }
    }
}

Ability 中声明事件订阅者

//事件订阅者
private NotificationEventSubscriber eventSubscriber;

Ability 中订阅事件, 用到MatchingSkills/CommonEventSubscribeInfo/CommonEventManager

/**
 * 订阅通用事件
 */
private void subscribeCommonEvent() {
    //
    MatchingSkills skills = new MatchingSkills();
    skills.addEvent(Const.NOTIFICATION_ACTION);
    //
    CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(skills);
    subscribeInfo.setThreadMode(CommonEventSubscribeInfo.ThreadMode.HANDLER);
    //
    eventSubscriber = new NotificationEventSubscriber(subscribeInfo, this);
    try {
        //
        CommonEventManager.subscribeCommonEvent(eventSubscriber);
    } catch (RemoteException e) {
        HiLog.error(LABEL_LOG, "%{public}s", "subscribeCommonEvent remoteException.");
    }
}

2.取消订阅

/**
 * 取消订阅
 */
private void unSubscribeCommonEvent() {
    try {
        //
        CommonEventManager.unsubscribeCommonEvent(eventSubscriber);
    } catch (RemoteException e) {
        HiLog.error(LABEL_LOG, "%{public}s", "unSubscribeCommonEvent remoteException.");
    }
}

3.发布普通通知

定义了一个公共通知主题,包括通知音、振动、锁屏显示和级别

/**
 * 定义通知槽
 */
private void defineNotificationSlot() {

    NotificationSlot notificationSlot =
            new NotificationSlot(Const.SLOT_ID, Const.SLOT_NAME, NotificationSlot.LEVEL_HIGH);
    //设置是否在收到通知时启用振动。
    notificationSlot.setEnableVibration(true);
    //设置锁屏可见性
    notificationSlot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);
    //设置声音
    Uri uri = Uri.parse(Const.SOUND_URI);
    notificationSlot.setSound(uri);
    try {
        //添加通知槽
        NotificationHelper.addNotificationSlot(notificationSlot);
    } catch (RemoteException ex) {
        HiLog.error(LABEL_LOG, "%{public}s", "defineNotificationSlot remoteException.");
    }
}

发布通知,用到NotificationRequest/NotificationRequest.NotificationNormalContent/NotificationRequest.NotificationContent/IntentAgent/IntentAgentConstant.OperationType/NotificationHelper

/**
 * 发布通知
 */
private void publishNotification() {
    notificationId = 0x1000001;
    NotificationRequest request = new NotificationRequest(notificationId).setSlotId(Const.SLOT_ID)
            .setTapDismissed(true);
    request.setContent(createNotificationContent(Const.NOTIFICATION_TITLE, Const.NOTIFICATION_CONTENT));
    IntentAgent intentAgent = createIntentAgent(MainAbility.class.getName(),
            IntentAgentConstant.OperationType.START_ABILITY);
    request.setIntentAgent(intentAgent);
    try {
        NotificationHelper.publishNotification(request);
    } catch (RemoteException ex) {
        HiLog.error(LABEL_LOG, "%{public}s", "publishNotification remoteException.");
    }
}

/**
 * 创建通知内容
 * @param title 标题
 * @param text  内容
 * @return
 */
private NotificationRequest.NotificationContent createNotificationContent(String title, String text) {
    NotificationRequest.NotificationNormalContent content= new NotificationRequest.NotificationNormalContent()
            .setTitle(title).setText(text);
    return new NotificationRequest.NotificationContent(content);
}

/**
 * 创建IntentAgent
 * @param ability own Ability
 * @param operationType
 * @return
 */
private IntentAgent createIntentAgent(String ability, IntentAgentConstant.OperationType operationType) {
    Intent intent = new Intent();
    Operation operation = new Intent.OperationBuilder().withAction(Const.NOTIFICATION_ACTION).build();
    intent.setOperation(operation);
    //标识使用 IntentAgent 的操作,例如启动能力或发送公共事件。
    if (operationType != IntentAgentConstant.OperationType.SEND_COMMON_EVENT) {
        intent.setElement(new ElementName("", Const.BUNDLE_NAME, ability));
    }
    List<Intent> intents = new ArrayList<>();
    intents.add(intent);
    //实例化IntentAgentInfo
    IntentAgentInfo agentInfo = new IntentAgentInfo(Const.REQUEST_CODE, operationType,
            IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG, intents, new IntentParams());

    return IntentAgentHelper.getIntentAgent(getContext(), agentInfo);
}

4.发布带有回复操作的通知

比普通通知多了NotificationUserInput/NotificationActionButton/NotificationConstant.SemanticActionButton

/**
 * 发布带有回复操作的通知
 */
private void publishNotificationWithAction() {
    notificationId = 0x1000002;
    //通知请求
    NotificationRequest request = new NotificationRequest(notificationId)
            .setSlotId(Const.SLOT_ID).setTapDismissed(true);
    request.setContent(createNotificationContent(Const.NOTIFICATION_TITLE2, Const.NOTIFICATION_CONTENT2));
    //实例化IntentAgent
    IntentAgent intentAgent = createIntentAgent(MainAbility.class.getName(),
            IntentAgentConstant.OperationType.SEND_COMMON_EVENT);
    request.setIntentAgent(intentAgent);
    //用户输入
    NotificationUserInput input = new NotificationUserInput.Builder(Const.NOTIFICATION_INPUT_KEY)
            .setTag(Const.NOTIFICATION_OPER_TITLE).build();
    //操作按钮
    NotificationActionButton actionButton = new NotificationActionButton
            .Builder(null, Const.NOTIFICATION_OPER_TITLE, intentAgent)
            .addNotificationUserInput(input)
            .setSemanticActionButton(NotificationConstant.SemanticActionButton.ARCHIVE_ACTION_BUTTON)
            .setAutoCreatedReplies(false)
            .build();
    //
    request.addActionButton(actionButton);
    try {
        //发布通知
        NotificationHelper.publishNotification(request);
    } catch (RemoteException ex) {
        HiLog.error(LABEL_LOG, "%{public}s", "publishNotificationWithAction remoteException.");
    }
}

5.取消通知/全部通知

/**
 * 取消通知
 */
private void cancel() {
    try {
        //
        NotificationHelper.cancelNotification(notificationId);
    } catch (RemoteException ex) {
        HiLog.error(LABEL_LOG, "%{public}s", "cancel remoteException.");
    }
}

/**
 * 取消所有通知
 */
private void cancelAll() {
    try {
        //
        NotificationHelper.cancelAllNotifications();
    } catch (RemoteException ex) {
        HiLog.error(LABEL_LOG, "%{public}s", "cancelAll remoteException.");
    }
}

6.主动 激活 IntentAgent

触发一个 IntentAgent,调用此方法后,将执行与指定的 IntentAgent 关联的事件,例如启动一个能力或发送一个普通事件。

/**
 * 主动 激活 IntentAgent
 * @param component
 */
private void proactiveActivateIntentAgent(Component component) {
    //触发一个 IntentAgent。
    //调用此方法后,将执行与指定的 IntentAgent 关联的事件,例如启动一个能力或发送一个普通事件。
    IntentAgentHelper.triggerIntentAgent(this, createIntentAgent(MainAbility.class.getName(),
            IntentAgentConstant.OperationType.START_ABILITY), null, null,
            new TriggerInfo(null, null, null, Const.REQUEST_CODE));
}

完整代码

附件直接下载

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
Notification.zip 1.29M 66次下载
3
收藏 3
回复
举报
1条回复
按时间正序
/
按时间倒序
Anzia
Anzia

wow,速度。我水了好久

回复
2021-8-11 00:26:24
回复
    相关推荐