【鸿蒙】通知

发布于:2024-05-01 ⋅ 阅读:(28) ⋅ 点赞:(0)

一、概要

Android的Notification。

说到通知,就想到了推送。
通知这块可以做到不像Android一样需要集成各家厂商的推送了,不知道是否有建立独立的推送系统

在这里插入图片描述
这是官网上介绍的跨APP进行的IPC通知。实际在Android开发过程中,可能这种场景会相对较少。当然,进行BroardCastReceiver方面的调用也是有的。

二、实现

1.通知的类型

普通文本、长文本、多行文本、图片类型、进度条通知。

好吧:文本这块划分确实有点多。就理解为文本、图片、进度条类型。
除此之外,并没有视频、聊天这种相对复杂一点的类型。

2.发送通知

import NotificationManager from '@ohos.notificationManager';

let notificationRequest = {
  id: 1,
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
      title: 'test_title',
      text: 'test_text',
      additionalText: 'test_additionalText',
    }
  }
}

NotificationManager.publish(notificationRequest, (err) => {
    if (err) {
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
    }
    console.info(`[ANS] publish success`);
});

在这里插入图片描述

3.通知的意图

是什么?
也就是消费通知。当然你可以认为显示也是一种消费,但这里的关注点在于用户点击通知之后的意图。
这里的意图是WantAgent——>Intent。

怎么做?

import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';

let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。

// 通过WantAgentInfo的operationType设置动作类型。
let wantAgentInfo = {
    wants: [
        {
            deviceId: '',
            bundleName: 'com.example.test',
            abilityName: 'com.example.test.MainAbility',
            action: '',
            entities: [],
            uri: '',
            parameters: {}
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
    if (err) {
        console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
    } else {
        console.info('[WantAgent]getWantAgent success');
        wantAgentObj = data;
    }
});

// 构造NotificationRequest对象
let notificationRequest = {
    content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
            title: 'Test_Title',
            text: 'Test_Text',
            additionalText: 'Test_AdditionalText',
        },
    },
    id: 1,
    label: 'TEST',
    wantAgent: wantAgentObj,
}

// 通知发送
NotificationManager.publish(notificationRequest, (err) => {
    if (err) {
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
    }
    console.info(`[ANS] publish success `);
});

三、总结

通知是个UI组件,它和BroadCastReceiver还是不同的。鸿蒙版本的通知较为基础。


网站公告

今日签到

点亮在社区的每一天
去签到