公共事件
事件(Event)是指对由系统、组件、应用程序等对象发起操作的封装。事件的发布者通常情况下会维持自己的状态不变,如果收到了某些交互操作所产生的信号而改变了他的状态,就会将消息发布给事件接收者,事件接收者是可以订阅用户或者相关的应用程序
公共事件(Common Event)是指通过广播的形式发出的事件,即一个事件发布者会将消息发送给多个事件接收者。
其实就是消息提示,以及下拉页面中的新闻这些(个人理解)
公共事件分类
-
系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户的应用程序。
-
自定义公共事件:应用程序定义的期望特定订阅者可以接受的公共事件。
公共事件开发
-
公共事件订阅开发
-
公共事件发布开发
-
公共事件取消订阅开发
公共事件处理接口
import commonEvent from '@hoos.commonEvent'
commonEvent.(后面可写)
-
publish(event: string, callback: AsyncCallback) ===发布公共事件
-
publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) ===制定发布信息并发布公共事件
-
createSubscriber(subscribeInfo:CommonEventSubscribeInfo ) ===创建订阅者对象(promise)
-
createSubscriber(subscribeInfo:CommonEventSubscribeInfo ,callback: AsyncCallback ) ===创建订阅者对象(callback)
-
subscribe(subscriber: CommonEventSubsriber, callback: AsyncCallback) ===订阅公共事件
-
unsubscribe(subscriber: CommonEventSubsriber, callback?: AsyncCallback) ===取消订阅公共事件
发布公共事件
-
有序公共事件:有序公共事件是指多个订阅者有依赖关系或者对处理顺序有要求,也就是订阅者有优先级。如果订阅者的优先级高,就优先接收处理公共事件。当公共事件发布数据中的属性isOrdered的值为真时,表示公共事件为有序公共事件
-
无序公共事件:无序公共事件没有优先级的概念,接收公共事件是不分顺序的,发布的无序公共事件类似于电台广播,接收者均可以接收到公共事件
-
黏性公共事件:黏性公共事件是指即使对公共事件的订阅操作是在发布公共事件之后进行的,订阅者也能收到的公共事件。当属性isSticky的值为真时表示为黏性公共事件。
-
带权限的公共事件:带权限的公共事件是指该公共事件有一定的访问权限,必须是有相应访问权限的订阅者才能接收到该公共事件的消息。它为公共事件提供了一定的安全机制。
发布公共事件代码实例
//发布没有指定信息的公共事件的示例
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)
}
}
订阅公共事件
-
导入commonEvent模块
import Base from '@ohos.base';
import commonEventManager from '@ohos.commonEventManager';
import promptAction from '@ohos.promptAction';
const TAG: string = 'ProcessModel';
2.创建订阅者信息
订阅者信息subscribeInfo的详细内容见上,其中events参数是必填的,他决定了所订阅的事件。
// 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
let subscriber: commonEventManager.CommonEventSubscriber | null = null;
// 订阅者信息,其中的event字段需要替换为实际的事件名称。
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
events: ['event'], // 订阅灭屏公共事件
};
3.创建订阅者
这里以回调方式返回,在创建成功后,保存订阅者对象subscriber,后续订阅者可以执行订阅或退订等操作。
// 创建订阅者回调
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; //保存订阅者
// 订阅公共事件回调
...
})
4.订阅公共事件
订阅公共事件前需要先创建订阅者,然后才能完成订阅。在订阅公共事件时要确定订阅回调函数,订阅者在接收到公共事件时会触发订阅公共事件订阅回调函数,该函数的参数会接收公共事件的数据,即data,其内部包含了当前接收的公共事件名称、公共事件的结果代码和自定义的结果数据等信息。订阅公共事件的示例代码如下:
// 订阅公共事件回调
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`);
}
5.取消订阅公共事件
订阅者可以调用CommonEvent中的 unsubscribe 方法来取消已经订阅的某个公共事件
if(this.subscriber != null)
commonEvent.unsubscribe(this.subscriber,(err) => {
if (err) {
console.error("取消订阅错误err =" + JSON.string.ify(err))
} else {
console.log("已取消订阅")
}
})
通知
应用程序除了可以发布公共事件,还可以发布通知
公共事件和通知的区别主要就在于接收者不同,通知的接收者通常是系统自带的通知栏。通知是用户获取必要信息的一种重要形式,在系统下拉的通知栏中显示。通知可以是接收的短消息、即时通信消息等,也可以是广告、版本更新、新闻通知等应用的推送消息,或者显示下载进度、正在播放的音乐等当前正在进行的事件。
通知接口
通知接口主要包括:
-
通知使能开关接口
-
通知订阅接口
-
通知订阅回调接口
-
发送通知接口
开发步骤
在进行通知开发时,都要先导入通知模块,代码如下:
import Notification from '@ohos.notification'
订阅通知:通知接收要做的第一件事是订阅,即需要向ANS通知子系统发起订阅请求。订阅通知首先需要定义订阅者信息,代码如下:
var subscriber = {
onConsume: function (data) { //定义通知回调函数
let req = data.request
console.info('onConsume callback req. id:' + req.id)
},
onCancel: function (data) { //定义通知取消回调函数
let req = data.request
console.info('onCancel callback req.id: :' + req.id)
},
onUpdate: function (data) { //定义通知排序更新回调函数
console.info('onUpdate in test')
},
onConnect: function () { //定义订阅成功回调函数
console.info('onConnect in test')
},
onDisconnect: function() { //定义取消订阅回调函数
console.info('onDisConnect in test')
}
}
通过系统提供的订阅接口,可以订阅通知,基本代码如下:
Notification.subscribe(subscriber, (err,data)=>{
if(err) {
console.error('订阅通知失败' + Json.stringify(err))
}
console.info('订阅通知成功' + JSON.stringify(data))
})
发布通知
发布普通类型文本通知
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)
}
}
发布进度条类型通知
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)
}
}
864

被折叠的 条评论
为什么被折叠?



