提交 22e4c8a3 编写于 作者: Z zengyawen

application-models

Signed-off-by: Nzengyawen <zengyawen1@huawei.com>
上级 adac20f8
# 公共事件与通知 # 通知
- [公共事件与通知概述](notification-brief.md) - [通知概述](notification-overview.md)
- [公共事件开发指导](common-event.md) - [订阅通知(仅对系统应用开放)](notification-subscription.md)
- [通知开发指导](notification-guidelines.md) - [使能通知开关](notification-enable.md)
- [调试助手使用指导](assistant-guidelines.md) - 发布通知
\ No newline at end of file - [发布基础类型通知](text-notification.md)
- [发布进度条类型通知](progress-bar-notification.md)
- [为通知添加行为意图](notification-with-wantagent.md)
\ No newline at end of file
# 调试助手使用指导
​ 公共事件与通知提供了供开发者查看公共事件信息及通知信息、发布公共事件等一些调试功能的工具。这些工具已经随系统集成,开发者进入shell环境,可以直接调用相关命令。
## cem调试助手
### publish
* 介绍
发布公共事件。
* 用法
`cem publish [<options>]`
参数如下表所示
| 参数 | 参数说明 |
| ------------ | ------------------------------------------ |
| -e/--event | 必选参数,发布事件名称 |
| -s/--sticky | 可选参数,发布粘性事件,默认发布非粘性事件 |
| -o/--ordered | 可选参数,发布有序事件,默认发布无序事件 |
| -c/--code | 可选参数,公共事件结果码 |
| -d/--data | 可选参数,公共事件携带数据 |
| -h/--help | 帮助信息 |
* 示例
`cem publish --event "testevent"`
发布名称为testevent的公共事件
![cem-publish-event](figures/cem-publish-event.png)
`cem publish -e "testevent" -s -o -c 100 -d "this is data" `
发布名称为testevent的粘性有序公共事件,该事件的结果码为100,携带数据内容为“this is data”
![cem-publish-all](figures/cem-publish-all.png)
### dump
* 介绍
打印公共事件相关信息。
* 用法
`cem dump [<options>]`
参数如下表所示
| 参数 | 参数说明 |
| ---------- | -------------------------------------------- |
| -a/--all | 打印开机以来所有已发送的公共事件及其具体信息 |
| -e/--event | 查询特定名称事件的具体信息 |
| -h/--help | 帮助信息 |
* 示例
`cem dump -e "testevent"`
​ 打印公共事件名称为testevent的具体信息。
​ ![cem-dump-e](figures/cem-dump-e.png)
### help
* 介绍
打印帮助信息。
* 用法
`cem help`
* 示例
![cem-help](figures/cem-help.png)
## anm调试助手
### dump
* 介绍
打印通知相关信息。
* 用法
`anm dump [<options>]`
参数如下表所示
| 参数 | 参数说明 |
| ---------------- | ---------------------------------------- |
| -A/--active | 打印所有活跃的通知信息 |
| -R/--recent | 打印最近的通知信息 |
| -D/--distributed | 打印来自其他设备的分布式通知信息 |
| --setRecentCount | 可选参数,设置打印最近的通知消息缓存个数 |
| -h/--help | 帮助信息 |
* 示例
`anm dump -A`
打印活跃的通知信息
![anm-dump-A](figures/anm-dump-A.png)
`anm dump --setRecentCount 10`
设置打印最近通知消息缓存数量为10
### help
* 介绍
打印帮助信息。
* 用法
`anm help`
* 示例
![anm-help](figures/anm-help.png)
\ No newline at end of file
# 公共事件开发指导
## 简介
OpenHarmony通过CES(Common Event Service,公共事件服务)为应用程序提供订阅、发布、退订公共事件的能力。
公共事件可分为系统公共事件和自定义公共事件。
+ 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 例如:系统关键服务发布的系统事件(例如:hap安装,更新,卸载等)。
+ 自定义公共事件:应用自定义一些公共事件用来实现跨应用的事件通信能力。
每个应用都可以按需订阅公共事件,订阅成功且公共事件发布,系统会把其发送给应用。这些公共事件可能来自系统、其他应用和应用自身。
## 公共事件订阅开发指导
### 场景介绍
当需要订阅某个公共事件,获取某个公共事件传递的参数时,可以创建一个订阅者对象,用于作为订阅公共事件的载体,订阅公共事件并获取公共事件传递而来的参数。订阅部分系统公共事件需要先申请权限,订阅这些事件所需要的权限请见[公共事件权限列表](../reference/apis/js-apis-commonEvent.md#权限列表)
### 接口说明
| 接口名 | 接口描述 |
| ---------------------------------------------------------------------------------------------- | ----------- |
| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | 创建订阅者对象(callback) |
| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | 创建订阅者对象(promise) |
| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | 订阅公共事件 |
### 开发步骤
1. 导入CommonEvent模块。
```js
import commonEvent from '@ohos.commonEvent';
```
2. 创建订阅者信息,详细的订阅者信息数据类型及包含的参数请见[CommonEventSubscribeInfo文档](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo)介绍。
```js
//用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
private subscriber = null
//订阅者信息
var subscribeInfo = {
events: ["event"],
}
```
3. 创建订阅者,保存返回的订阅者对象subscriber,用于执行后续的订阅、退订等操作。
```js
//创建订阅者回调
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err.code) {
console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]CreateSubscriber")
this.subscriber = subscriber
this.result = "Create subscriber succeed"
}
})
```
4. 创建订阅回调函数,订阅回调函数会在接收到事件时触发。订阅回调函数返回的data内包含了公共事件的名称、发布者携带的数据等信息,公共事件数据的详细参数和数据类型请见[CommonEventData文档](../reference/apis/js-apis-commonEvent.md#commoneventdata)介绍。
```js
//订阅公共事件回调
if (this.subscriber != null) {
commonEvent.subscribe(this.subscriber, (err, data) => {
if (err.code) {
console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data))
this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code
}
})
this.result = "Subscribe succeed"
} else {
prompt.showToast({ message: "Need create subscriber" })
}
```
## 公共事件发布开发指导
### 场景介绍
当需要发布某个自定义公共事件时,可以通过此方法发布事件。发布的公共事件可以携带数据,供订阅者解析并进行下一步处理。
### 接口说明
| 接口名 | 接口描述 |
| ---------------------------------- | ------ |
| publish(event: string, callback: AsyncCallback) | 发布公共事件 |
| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | 指定发布信息并发布公共事件 |
### 开发步骤
#### 发布公共事件开发步骤
1. 导入CommonEvent模块。
```js
import commonEvent from '@ohos.commonEvent';
```
2. 传入需要发布的事件名称和回调函数,发布事件。
```js
//发布公共事件
commonEvent.publish("event", (err) => {
if (err.code) {
console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
} else {
console.info("[CommonEvent]Publish1")
}
})
```
#### 指定发布信息发布公共事件的开发步骤
1. 导入CommonEvent模块。
```js
import commonEvent from '@ohos.commonEvent'
```
2. 定义发布事件时需要指定的发布信息,发布信息所包含的详细参数及其参数类型请见[CommonEventPublishData文档](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata)介绍。
```js
//公共事件相关信息
var options = {
code: 1, //公共事件的初始代码
data: "initial data",//公共事件的初始数据
}
```
3. 传入需要发布的事件名称、需要发布的指定信息和回调函数,发布事件。
```js
//发布公共事件
commonEvent.publish("event", options, (err) => {
if (err.code) {
console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
} else {
console.info("[CommonEvent]Publish2")
}
})
```
## 公共事件取消订阅开发指导
### 场景介绍
订阅者需要取消已订阅的某个公共事件时,可以通过此方法取消订阅事件。
### 接口说明
| 接口名 | 接口描述 |
| ---------------------------------- | ------ |
| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | 取消订阅公共事件 |
### 开发步骤
1. 导入CommonEvent模块。
```js
import commonEvent from '@ohos.commonEvent';
```
2. 根据[公共事件订阅指导](#公共事件订阅开发指导)的步骤来订阅某个事件。
3. 调用CommonEvent中的unsubscribe方法取消订阅某事件。
```js
if (this.subscriber != null) {
commonEvent.unsubscribe(this.subscriber, (err) => {
if (err.code) {
console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]Unsubscribe")
this.subscriber = null
this.result = "Unsubscribe succeed"
}
})
}
```
## 相关实例
针对公共事件开发,有以下相关实例可供参考:
- [`CommonEvent`:订阅公共事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CommonEvent)
# 公共事件与通知开发概述
公共事件与通知提供了应用程序向系统其他应用程序发布消息、接收来自系统或其他应用特定消息的能力,这些消息可以是新闻推送、广告通知或者预警信息等。
CES(Common Event Service, 即公共事件服务)为应用程序提供发布、订阅及退订公共事件的能力。公共事件根据事件发送方不同可分为系统公共事件和自定义公共事件。
![ces](figures/ces.png)
- 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 公共事件包括:终端设备用户可感知的亮灭屏事件,以及系统关键服务发布的系统事件(例如:USB插拔,网络连接,系统升级)等。
- 自定义公共事件:由应用自身定义的期望特定订阅者可以接收到的公共事件,这些公共事件往往与应用自身的业务逻辑相关。
ANS(Advanced Notification Service,即通知系统服务)为应用程序提供发布通知的能力。这些通知常见的使用场景如下:
- 显示接收到的短消息、即时通讯消息等;
- 显示应用的推送消息,如广告、版本更新、新闻通知等;
- 显示当前正在进行的事件,如播放音乐、导航信息、下载进度等。
通知消息将显示在系统下拉菜单栏,用户可对通知消息进行删除操作,或点击通知触发进一步的操作。
![ans](figures/ans.png)
# 使能通知开关
应用需要开启通知开关才能发送通知。开发者可以在通知发布前调用[requestEnableNotification()](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8)方法,弹窗让用户选择是否开启使能开关,仅弹窗一次,后续调用该接口不再弹窗。
**图1** 使能通知开关示意图
![zh-cn_image_0000001416585590](figures/zh-cn_image_0000001416585590.png)
- 点击“允许”后,则表示允许应用发送通知。
- 点击“取消”后,再次调用[requestEnableNotification()](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8)方法,则不再弹窗。此时如需要手动使能通知开关,操作步骤如下所示。
1. 从设备左上方下拉,进入通知界面。
![zh-cn_image_0000001417062434](figures/zh-cn_image_0000001417062434.png)
2. 点击右上角“设置”图标,进入通知界面,找到需要打开通知开关的应用。
![zh-cn_image_0000001466462297](figures/zh-cn_image_0000001466462297.png)
3. 打开“允许通知”开关。
![zh-cn_image_0000001466782025](figures/zh-cn_image_0000001466782025.png)
## 接口说明
详细接口见[接口文档](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8)
**表1** 通知开关接口功能介绍
| **接口名** | **描述** |
| -------- | -------- |
| isNotificationEnabled(bundle:&nbsp;BundleOption,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;):&nbsp;void | 查询通知开关。<br/>**说明:**<br/>仅支持系统应用调用。 |
| enableNotification(bundle:&nbsp;BundleOption,&nbsp;enable:&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 设置通知开关。例如在“设置&nbsp;&gt;&nbsp;应用和服务&nbsp;&gt;&nbsp;应用管理”,进入对应应用信息的“通知管理”中设置通知开关状态。<br/>**说明:**<br/>仅支持系统应用调用。 |
| requestEnableNotification(callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 请求发送通知的许可,第一次调用弹窗供用户选择允许或禁止。 |
## 开发步骤
1. 导入NotificationManager模块。
```ts
import NotificationManager from '@ohos.notificationManager';
```
2. 请求发送通知的许可。
```ts
NotificationManager.requestEnableNotification().then(() => {
console.info(`[ANS] requestEnableNotification success`);
}).catch((err) => {
console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`);
});
```
# 通知开发指导
## 场景简介
OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对通知类型的消息进行管理,支持多种通知类型,包括文本,长文本,多文本,图片,社交,媒体等。所有系统服务以及应用都可以通过通知接口发送通知消息,用户可以通过SystemUI查看所有通知消息。
通知常见的使用场景:
- 显示接收到短消息、即时消息等。
- 显示应用的推送消息,如广告、版本更新等。
- 显示当前正在进行的事件,如导航、下载等。
## 通知流程
通知业务流程由ANS通知子系统、通知发送端、通知订阅端组成。
一条通知从通知发送端产生,通过IPC通信发送到ANS,ANS再分发给通知订阅端。
系统应用还支持通知相关配置,如使能开关、配置参数由系统配置发起请求,发送到ANS存储到内存和数据库。
![1648113187545](figures/notification.png)
## 接口说明
部分接口仅系统应用才可以调用,且需要具备权限:SystemCapability.Notification.Notification ,接口返回值有两种返回形式:callback和promise,下表中为callback形式接口,promise和callback只是返回值方式不一样,功能相同,具体API说明详见[接口文档](../reference/apis/js-apis-notification.md)
**表1** 通知使能开关接口功能介绍
| 接口名 | 描述 |
| ------------------------------------------------------------ | ---------------- |
| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\<boolean>): void | 查询通知使能开关 |
| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void>): void | 设置使能开关 |
用于查询和设置通知使能开关,若某个应用的通知使能关闭状态,则无法发送通知。
**表2** 通知订阅接口功能介绍
| 接口名 | 描述 |
| ------------------------------------------------------------ | ---------------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void>): void | 订阅指定应用通知 |
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | 订阅所有通知 |
| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | 取消订阅通知 |
订阅接口有支持订阅所有通知、或订阅某些应用的通知。
**表3** 通知订阅回调接口功能介绍
| 接口名 | 描述 |
| ------------------------------------------------ | ---------------- |
| onConsume?:(data: SubscribeCallbackData) => void | 通知回调 |
| onCancel?:(data: SubscribeCallbackData) => void | 通知取消回调 |
| onUpdate?:(data: NotificationSortingMap) => void | 通知排序更新回调 |
| onConnect?:() => void; | 订阅成功回调 |
| onDisconnect?:() => void; | 取消订阅回调 |
**表4** 发送通知接口功能介绍
| 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------ |
| publish(request: NotificationRequest, callback: AsyncCallback\<void>): void | 发布通知 |
| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\<void>): void | 指定用户发布通知 |
| cancel(id: number, label: string, callback: AsyncCallback\<void>): void | 取消指定的通知 |
| cancelAll(callback: AsyncCallback\<void>): void; | 取消所有该应用发布的通知 |
携带userId的publish接口,可以指定向该用户下订阅者发布通知。
## 开发指导
通知的开发步骤一般是订阅通知、开启通知使能、发布通知。
### 导入模块
```js
import Notification from '@ohos.notification';
```
### 通知订阅
通知接受端首选需要向通知子系统发起通知订阅。
```js
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===>');
},
onDestroy: function () {
console.info('===>onDestroy in test===>');
},
};
Notification.subscribe(subscriber, (err, data) => { // callback形式调用异步接口
if (err.code) {
console.error('===>failed to subscribe because ' + JSON.stringify(err));
return;
}
console.info('===>subscribeTest success : ' + JSON.stringify(data));
});
```
### 通知发送
##### 开启通知使能
应用发布通知的使能开关默认是关闭的,需要通过下拉通知栏,在通知设置里打开通知开关。应用也可以通过调用Notification.requestEnableNotification接口,弹窗提示用户是否允许发送通知。
```js
Notification.requestEnableNotification().then((data) => {
console.info('===>requestEnableNotification success');
}).catch((err) => {
console.error('===>requestEnableNotification failed because ' + JSON.stringify(err));
});
```
##### 通知发布
发布通知,先要构造NotificationRequest对象,设置通知类型、标题、内容等一系列属性。下面以发布普通文本和携带wantAgent通知为例。
普通文本通知实例
```js
//构造NotificationRequest对象
var notificationRequest = {
id: 1,
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "test_title",
text: "test_text",
additionalText: "test_additionalText"
}
}
}
//通知发送
Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
携带wantAgent通知实例
wantAgent使用详见[wantAgent开发文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/wantagent.md)
- 创建wantAgent对象
```js
import wantAgent from '@ohos.wantAgent';
//WantAgentInfo对象
var wantAgentInfo = {
wants: [
{
bundleName: 'ohos.samples.eTSNotification',
abilityName: 'ohos.samples.eTSNotification.MainAbility',
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
//wantAgent对象
var WantAgent;
//getWantAgent回调
function getWantAgentCallback(err, data) {
console.info("===>getWantAgentCallback===>");
if (err.code == 0) {
WantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// 获取wantAgent对象
wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
```
- 发布通知
```js
//构造NotificationRequest对象
var notificationRequest = {
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "AceApplication_Title",
text: "AceApplication_Text",
additionalText: "AceApplication_AdditionalText"
},
},
id: 1,
label: 'TEST',
wantAgent: WantAgent,
slotType: Notification.SlotType.OTHER_TYPES,
deliveryTime: new Date().getTime()
}
//通知发送
Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
- 取消通知
取消通知可以分成取消指定的单条通知和取消所有通知,应用只能取消自己发布的通知。
```js
//cancel回调
function cancelCallback(err) {
console.info("===>cancelCallback===>");
}
Notification.cancel(1, "label", cancelCallback)
```
## 相关实例
针对通知开发,有以下相关可供参考:
- [`Notification:`订阅、发送通知(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/Notification)
# 通知概述
## 通知简介
所有系统服务以及应用都可以通过通知接口发送通知消息,用户可以通过通知栏查看通知内容,也可以点击通知来打开应用。
通知常见的使用场景:
- 显示接收到的短消息、即时消息等。
- 显示应用的推送消息,如广告、版本更新等。
- 显示当前正在进行的事件,如下载等。
OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对通知类型的消息进行管理,支持多种通知类型,如基础类型通知、进度条类型通知、后台代理提醒。
## 通知业务流程
通知业务流程由通知子系统、通知发送端、通知订阅端组成。
一条通知从通知发送端产生,通过[IPC通信](../connectivity/ipc-rpc-overview.md)发送到通知子系统,再由通知子系统分发给通知订阅端。
系统应用还支持通知相关配置,如使能开关、配置参数由系统配置发起请求,发送到通知子系统存储到内存和数据库。
![zh-cn_image_0000001466582017](figures/zh-cn_image_0000001466582017.png)
# 订阅通知(仅对系统应用开放)
应用需要接收通知,必须先发起订阅,通知子系统提供两种接口:订阅所有应用发布的通知和订阅某些应用发布的通知。
系统提供NotificationSubscriber对象,用于提供订阅成功、通知接收、通知取消、订阅取消等回调接口,将变化信息回调给订阅者。
## 接口说明
通知订阅主要接口如下。详细接口介绍请参见[API参考](../reference/apis/js-apis-notification.md#notification%E6%A8%A1%E5%9D%97)
**表1** 通知订阅接口介绍
| **接口名** | **描述** |
| -------- | -------- |
| subscribe(subscriber:&nbsp;NotificationSubscriber,&nbsp;info:&nbsp;NotificationSubscribeInfo,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 订阅指定应用通知。 |
| subscribe(subscriber:&nbsp;NotificationSubscriber,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 订阅所有通知。 |
**表2** 通知订阅回调接口介绍
| | |
| -------- | -------- |
| **接口名** | **描述** |
| onConsume?:(data:&nbsp;SubscribeCallbackData)&nbsp;=&gt;&nbsp;void | 通知回调。 |
| onCancel?:(data:&nbsp;SubscribeCallbackData)&nbsp;=&gt;&nbsp;void | 通知取消回调。 |
| onUpdate?:(data:&nbsp;NotificationSortingMap)&nbsp;=&gt;&nbsp;void | 通知排序更新回调。 |
| onConnect?:()&nbsp;=&gt;&nbsp;void; | 订阅成功回调。 |
| onDisconnect?:()&nbsp;=&gt;&nbsp;void; | 取消订阅回调。 |
| onDestroy?:()&nbsp;=&gt;&nbsp;void | 与通知子系统断开回调。 |
| onDoNotDisturbDateChange?:(mode:&nbsp;notification.DoNotDisturbDate)&nbsp;=&gt;&nbsp;void | 免打扰时间选项变更回调。 |
| onEnabledNotificationChanged?:(callbackData:&nbsp;EnabledNotificationCallbackData)&nbsp;=&gt;&nbsp;void | 通知开关变更回调。 |
## 开发步骤
1. 申请`ohos.permission.NOTIFICATION_CONTROLLER`权限,配置方式请参阅[访问控制授权申请指导](../security/accesstoken-guidelines.md#stage%E6%A8%A1%E5%9E%8B)
2. 导入通知订阅模块。
```ts
import NotificationSubscribe from '@ohos.notificationSubscribe';
```
3. 创建订阅者对象。
```ts
let subscriber = {
onConsume: function (data) {
let req = data.request;
console.info('[ANS] onConsume callback req.id: ' + req.id);
},
onCancel: function (data) {
let req = data.request;
console.info('[ANS] onCancel callback req.id: : ' + req.id);
},
onUpdate: function (data) {
console.info('[ANS] onUpdate in test');
},
onConnect: function () {
console.info('[ANS] onConnect in test');
},
onDisconnect: function () {
console.info('[ANS] onDisConnect in test');
},
onDestroy: function () {
console.info('[ANS] onDestroy in test');
},
};
```
4. 发起通知订阅。
```ts
NotificationSubscribe.subscribe(subscriber, (err, data) => { // callback形式调用异步接口
if (err) {
console.error(`[ANS] failed to subscribe, error[${err}]`);
return;
}
console.info(`[ANS] subscribeTest success : + ${data}`);
});
```
# 为通知添加行为意图
WantAgent提供了封装行为意图的能力,这里所说的行为意图主要是指拉起指定的应用组件及发布公共事件等能力。OpenHarmony支持以通知的形式,将WantAgent从发布方传递至接收方,从而在接收方触发WantAgent中指定的意图。例如,在通知消息的发布者发布通知时,通常期望用户可以通过通知栏点击拉起目标应用组件。为了达成这一目标,开发者可以将WantAgent封装至通知消息中,当系统接收到WantAgent后,在用户点击通知栏时触发WantAgent的意图,从而拉起目标应用组件。
为通知添加行为意图的实现方式如下图所示:发布通知的应用向应用组件管理服务AMS(Ability Manager Service)申请WantAgent,然后随其他通知信息一起发送给桌面,当用户在桌面通知栏上点击通知时,触发WantAgent动作。
**图1** 携带行为意图的通知运行机制
![notification-with-wantagent](figures/notification-with-wantagent.png)
## 接口说明
具体接口描述,详见[WantAgent接口文档](../reference/apis/js-apis-wantAgent.md#wantagent%E6%A8%A1%E5%9D%97)
| | |
| -------- | -------- |
| **接口名** | **描述** |
| getWantAgent(info:&nbsp;WantAgentInfo,&nbsp;callback:&nbsp;AsyncCallback&lt;WantAgent&gt;):&nbsp;void | 创建WantAgent。 |
| trigger(agent:&nbsp;WantAgent,&nbsp;triggerInfo:&nbsp;TriggerInfo,&nbsp;callback?:&nbsp;Callback&lt;CompleteData&gt;):&nbsp;void | 触发WantAgent意图。 |
| cancel(agent:&nbsp;WantAgent,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 取消WantAgent。 |
| getWant(agent:&nbsp;WantAgent,&nbsp;callback:&nbsp;AsyncCallback&lt;Want&gt;):&nbsp;void | 获取WantAgent的want。 |
| equal(agent:&nbsp;WantAgent,&nbsp;otherAgent:&nbsp;WantAgent,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;):&nbsp;void | 判断两个WantAgent实例是否相等。 |
## 开发步骤
1. 导入模块。
```ts
import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```
2. 创建WantAgentInfo信息。
场景一:创建拉起Ability的WantAgent的WantAgentInfo信息。
```ts
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的WantAgentInfo信息。
```ts
let wantAgentObj = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。
// wantAgentInfo
let wantAgentInfo = {
wants: [
{
action: 'event_name', // 设置事件名。
parameters: {},
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
}
```
3. 创建WantAgent。
```ts
// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
if (err) {
console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
} else {
console.info('[WantAgent]getWantAgent success');
wantAgentObj = data;
}
});
```
4. 构造NotificationRequest对象。
```ts
// 构造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,
}
```
5. 发布WantAgent通知。
```ts
// 通知发送
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
```
6. 用户通过点击通知栏上的通知,触发WantAgent的动作。
```ts
// 触发WantAgent
let triggerInfo = {
code: 0
}
wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => {
console.info('[WantAgent]getWantAgent success, completeData: ', + JSON.stringify(completeData));
});
```
# 发布进度条类型通知
进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度显示。OpenHarmony提供了进度条模板,发布通知应用设置好进度条模板的属性值,如模板名、模板数据,通过通知子系统发送到通知栏显示。
目前系统模板仅支持进度条模板,通知模板[NotificationTemplate](../reference/apis/js-apis-notification.md#notificationtemplate8)中的data参数为用户自定义数据,用于显示与模块相关的数据,效果示意如下图所示。
![zh-cn_image_0000001416903138](figures/zh-cn_image_0000001416903138.png)
## 接口说明
[isSupportTemplate()](../reference/apis/js-apis-notification.md#notificationissupporttemplate8)是查询模板是否支持接口,目前仅支持进度条模板。
| | |
| -------- | -------- |
| **接口名** | **描述** |
| isSupportTemplate(templateName:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;):&nbsp;void | 查询模板是否存在。 |
## 开发步骤
1. [使能通知开关](notification-enable.md),获得用户授权后,才能使用通知功能。
2. 导入模块。
```ts
import NotificationManager from '@ohos.notificationManager';
```
3. 查询系统是否支持进度条模板,查询结果为支持downloadTemplate模板类通知。
```ts
NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`);
let isSupportTpl: boolean = data; // isSupportTpl的值为true表示支持支持downloadTemplate模板类通知,false表示不支持
// ...
}).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 查询系统支持进度条模板后,再进行后续的步骤操作。
4. 构造进度条模板对象,并发布通知。
```ts
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText'
}
},
// 构造进度条模板,name字段当前需要固定配置为downloadTemplate
template: {
name: 'downloadTemplate',
data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 }
}
}
// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
```
# 发布基础类型通知
基础类型通知主要应用于发送短信息、提示信息、广告推送等,支持普通文本类型、长文本类型、多行文本类型和图片类型。
**表1** 基础类型通知中的内容分类
| 类型 | 描述 |
| -------- | -------- |
| NOTIFICATION_CONTENT_BASIC_TEXT | 普通文本类型。 |
| NOTIFICATION_CONTENT_LONG_TEXT | 长文本类型。 |
| NOTIFICATION_CONTENT_MULTILINE | 多行文本类型。 |
| NOTIFICATION_CONTENT_PICTURE | 图片类型。 |
目前系统仅通知栏订阅了通知,将通知显示在通知栏里。基础类型通知呈现效果示意图如下所示。
**图1** 基础类型通知呈现效果示意图  ![zh-cn_image_0000001466462305](figures/zh-cn_image_0000001466462305.png)
## 接口说明
通知发布接口如下表所示,不同发布类型通知由[NotificationRequest](../reference/apis/js-apis-notification.md#notificationrequest)的字段携带不同的信息。
| **接口名** | **描述** |
| -------- | -------- |
| publish(request:&nbsp;NotificationRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 发布通知。 |
| cancel(id:&nbsp;number,&nbsp;label:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 取消指定的通知。 |
| cancelAll(callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void; | 取消所有该应用发布的通知。 |
## 开发步骤
1. [使能通知开关](notification-enable.md),获得用户授权后,才能使用通知功能。
2. 导入模块。
```ts
import NotificationManager from '@ohos.notificationManager';
```
3. 构造NotificationRequest对象,并发布通知。
- 普通文本类型通知由标题、文本内容和附加信息三个字段组成,其中标题和文本内容是必填字段,大小均需要小于200字节。
```ts
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`);
});
```
运行效果如下图所示。
![zh-cn_image_0000001466782033](figures/zh-cn_image_0000001466782033.png)
- 长文本类型通知继承了普通文本类型的字段,同时新增了长文本内容、内容概要和通知展开时的标题,其中长文本内容不超过1024字节,其他字段小于200字节。通知默认显示与普通文本相同,展开后,标题显示为展开后标题内容,内容为长文本内容。
```ts
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 长文本类型通知
longText: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
longText: 'test_longText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
}
}
}
// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
运行效果如下图所示。
![zh-cn_image_0000001416745530](figures/zh-cn_image_0000001416745530.png)
- 多行文本类型通知继承了普通文本类型的字段,同时新增了多行文本内容、内容概要和通知展开时的标题,其字段均小于200字节。通知默认显示与普通文本相同,展开后,标题显示为展开后标题内容,多行文本内容多行显示。
```ts
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
multiLine: {
title: 'test_title',
text: 'test_text',
briefText: 'test_briefText',
longTitle: 'test_longTitle',
lines: ['line_01', 'line_02', 'line_03', 'line_04'],
}
}
}
// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
运行效果如下图所示。
![zh-cn_image_0000001417062446](figures/zh-cn_image_0000001417062446.png)
- 图片类型通知继承了普通文本类型的字段,同时新增了图片内容、内容概要和通知展开时的标题,图片内容为PixelMap型对象,其大小不能超过2M。
```ts
let notificationPicture: PixelMap = undefined; // 需要获取图片PixelMap信息
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
picture: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
picture: notificationPicture
}
}
}
// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
```
运行效果如下图所示。
![zh-cn_image_0000001466582045](figures/zh-cn_image_0000001466582045.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册