HarmonyOS的公共事件与通知笔记
公共事件与通知
鸿蒙(HarmonyOS)的公共事件与通知是其系统中用于应用程序间通信和事件处理的重要机制。公共事件是指通过广播的形式发出的事件,即一个事件发布者会将消息发给多个事件接受者。通知与公共事件的主要区别是接收者不同,通知的接收者通常是系统自带的通知栏。本文主要介绍关于公共事件与通知的基本知识。
一、公共事件
公共事件是指通过广播的形式发出的事件,即一个事件发布者会将消息发给多个事件接受者。
公共事件发布者可以是系统、应用程序自身或者其他应用程序。
1.基础概念
1.1.公共事件分类
- 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户的应用程序。
- 自定义公共事件:应用程序定义的期望特定订阅者可以接受的公共事件。
1.2.公共事件的开发
- 公共事件订阅开发
- 公共事件发布开发
- 公共事件取消订阅开发
1.3.公共事件处理接口
import commonEvent from '@hoos.commonEvent'
1.4.自定义公共事件的类型
- 有序公共事件:多个订阅者有依赖关系或者对处理顺序有要求,也就是订阅者有优先级。如果订阅者的优先级高,优先处理公共事件内容或处理结果,甚至终止公共事件。低优先级的订阅者依赖于高优先级订阅者对该事件的处理结果。当公共事件发布数据的属性isOrdered的值为真时,为有序公共事件
- 无需公共事件:没有优先级概念,相当于广播
- 带权限的公共事件:即使订阅操作是发布公共事件之后进行的,订阅者也能收到公共事件
- 粘性公共事件:该公共事件有一定访问权限,为公共事件提供了一定的安全机制
2.具体实现
2.1发布公共事件
发布没有指定信息的公共事件的示例:
import Base from '@ohos.base';
import commonEventManager from '@ohos.commonEventManager';
const TAG: string = 'ProcessModel';
// 发布公共事件,其中的event字段需要替换为实际的事件名称。
commonEventManager.publish('event', (err: Base.BusinessError) => {
if (err) {
console.info(`PublishCallBack err = ${JSON.stringify(err)}`);
} else {
console.info(`Publish successfulaaaaa`);
}
});
@Entry
@Component
struct Index {
@State i: number = 1
build() {
Column() {
Text(`数据 ${this.i}`)
.fontSize(50)
Button('按钮')
.onClick(() => {
this.i += this.i
})
.width('100%')
.padding(20)
.margin(20)
}
.padding(20)
}
}
2.2订阅公共事件
2.2.1.导入模块
import Base from '@ohos.base';
import commonEventManager from '@ohos.commonEventManager';
import promptAction from '@ohos.promptAction';
const TAG: string = 'ProcessModel';
2.2.2.创建订阅者信息
// 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
let subscriber: commonEventManager.CommonEventSubscriber | null = null;
// 订阅者信息,其中的event字段需要替换为实际的事件名称。
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
events: ['event'], // 订阅灭屏公共事件
};
2.2.3.创建订阅者
// 创建订阅者回调
commonEventManager.createSubscriber(subscribeInfo, (err: Base.BusinessError, data: commonEventManager.CommonEventSubscriber) => {
if (err) {
console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Succeeded in creating subscriber.');
subscriber = data;
// 订阅公共事件回调
...
})
2.2.4.订阅公共事件
// 订阅公共事件回调
if (this.subscriber !== null) {
commonEventManager.subscribe(subscriber, (err: Base.BusinessError, data: commonEventManager.CommonEventData) => {
if (err) {
console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
return;
}
})
} else {
console.error(`Need create subscriber`);
}
2.2.5.取消订阅公共事件
if(this.subscriber != null)
commonEvent.unsubscribe(this.subscriber,(err) => {
if (err) {
console.error("取消订阅错误err =" + JSON.string.ify(err))
} else {
console.log("已取消订阅")
}
})
二、通知
注意:
在新的虚拟机和手机中通知开关是默认关闭的。可以通过
进入手机——设置——通知和状态栏——具体应用
里打开允许通知,否则将无法在通知栏显示。
1.基础概念
HarmonyOS通过使用高级通知服务(Advanced Notification Service,ANS)为应用程序提供了发布通知的能力。
应用可以把通知发布给ANS,ANS接受通知并进行管理。ANS支持多种通知类型,包括文本、长文本、多文本、图片、社交、媒体等。
1.1通知接口
通知接口主要包括:
- 通知使能开关接口
- 通知订阅接口
- 通知订阅回调接口
- 发送通知接口
1.2开发步骤
1.2.1.订阅通知
1.2.2.开启通知使能开关
即上述注意事项,打开允许通知开关。
1.2.3.发布通知
1.3功能
- 文本类型通知:支持普通文本类型和多文本类型
- 进度条类型通知
- 为通知添加行为意图
2.具体实现
2.1发布普通类型文本通知
import notificationManager from '@ohos.notificationManager';
import Base from '@ohos.base';
//构造notificationRequest对象
let notificationRequest: notificationManager.NotificationRequest = {
id: 1,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
}
}
};
//调用接口,传递已经构造的对象
notificationManager.publish(notificationRequest, (err:Base.BusinessError) => {
if (err) {
console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Succeeded in publishing notification.');
});
//不用在意应用显示
@Entry
@Component
struct Index {
@State i: number = 1
build() {
Column() {
Text(`数据 ${this.i}`)
.fontSize(50)
Button('按钮')
.onClick(() => {
this.i += this.i
})
.width('100%')
.padding(20)
.margin(20)
}
.padding(20)
}
}
上述代码运行成功后在日志中可以找到相关显示。
2.2发布进度条类型通知
import notificationManager from '@ohos.notificationManager';
import Base from '@ohos.base';
let notificationRequest: notificationManager.NotificationRequest = {
id: 5,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText'
}
},
// 构造进度条模板,name字段当前需要固定配置为downloadTemplate
template: {
name: 'downloadTemplate',
data: { title: '《丑八怪》', fileName: 'music.mp4', progressValue: 45 }
}
}
// 发布通知
notificationManager.publish(notificationRequest, (err:Base.BusinessError) => {
if (err) {
console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Succeeded in publishing notification.');
});
@Entry
@Component
struct Index {
@State i: number = 1
build() {
Column() {
Text(`数据 ${this.i}`)
.fontSize(50)
Button('按钮')
.onClick(() => {
this.i += this.i
})
.width('100%')
.padding(20)
.margin(20)
}
.padding(20)
}
}