创建通知
发布普通文本类型通知
export function publishTextNotification(title: string) {
let notificationReq: notificationManager.NotificationRequest = {
id: 1,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "通知标题",
text: '通知内容详情'
}
}
}
notificationManager.publish(notificationReq).then(() => {
console.info("publish success")
})
}
发布进度类型通知
aboutToAppear() {
// 1. 请求通知权限
openNotificationPermission();
let bundleName = this.context.abilityInfo.bundleName;
let abilityName = this.context.abilityInfo.name;
// 2. 创建want
createWantAgent(bundleName, abilityName).then(want => {
this.wantAgentObj = want;
}).catch((err: Error) => {
Logger.error(`getWantAgent fail, err: ${JSON.stringify(err)}`);
});
// 3. 判断当前设备是否支持notification downloadTemplate模版
notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
if (!isSupport) {
promptAction.showToast({
message: $r('app.string.invalid_button_toast')
})
}
this.isSupport = isSupport;
});
}
/**
* Obtains the WantAgent of an application.
*
* @returns WantAgent of an application.
*/
export function createWantAgent(bundleName: string, abilityName: string): Promise<object> {
let wantAgentInfo = {
wants: [
{
bundleName: bundleName,
abilityName: abilityName
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
} as wantAgent.WantAgentInfo;
return wantAgent.getWantAgent(wantAgentInfo);
}
/**
* Publish notification.
*
* @param progress Download progress
* @param title Notification title.
* @param wantAgentObj The want of application.
*/
export function publishNotification(progress: number, title: string, wantAgentObj: object) {
let template:notificationManager.NotificationTemplate = {
name: 'downloadTemplate',
data: {
title: `${title}`,
fileName: `${title}:${CommonConstants.DOWNLOAD_FILE}`,
progressValue: progress,
progressMaxValue: CommonConstants.PROGRESS_TOTAL,
isProgressIndeterminate: false
}
};
let notificationRequest: notificationManager.NotificationRequest = {
id: CommonConstants.NOTIFICATION_ID,
notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
// Construct a progress bar template. The name field must be set to downloadTemplate.
template: template,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: `${title}:${CommonConstants.DOWNLOAD_FILE}`,
text: ' ',
additionalText: `${progress}%`
}
},
wantAgent: wantAgentObj
};
notificationManager.publish(notificationRequest).catch((err: Error) => {
Logger.error(`[ANS] publish failed,message is ${err}`);
});
}
/**
* open notification permission
*/
export function openNotificationPermission() {
notificationManager.requestEnableNotification().then(() => {
Logger.info('Enable notification success');
}).catch((err:Error) => {
Logger.error('Enable notification failed because ' + JSON.stringify(err));
});
}
更新通知
在发出通知后,使用您之前使用的相同通知ID,再次调用notificationManager.publish来实现通知的更新。如果之前的通知是关闭的,将会创建新通知。
移除通知
通过通知ID和通知标签取消已发布的通知。
notificationManager.cancel(notificationId)
取消所有已发布的通知。
notificationManager.cancelAll()
设置通知通道
通过通知通道,您可让通知有不同的表现形式,比如社交类型的通知是横幅显示的,并且有提示音,而一般的通知则不会横幅显示,您可以使用slotType来实现,设置slotType为SlotType.SOCIAL_COMMUNICATION,表示为社交类型通知。示例代码如下
notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => {
console.info("addSlot success");
}).catch((err: Base.BusinessError) => {
console.error(`addSlot fail: ${JSON.stringify(err)}`);
});
通知通道类型主要有以下几种:
SlotType.SOCIAL_COMMUNICATION:社交类型,状态栏中显示通知图标,有横幅和提示音。
SlotType.SERVICE_INFORMATION:服务类型,状态栏中显示通知图标,没有横幅但有提示音。
SlotType.CONTENT_INFORMATION:内容类型,状态栏中显示通知图标,但没有横幅或提示音。
SlotType.OTHER_TYPES:其它类型,状态栏中不显示通知图标,且没有横幅或提示音。
创建通知组
将不同类型的通知分为不同的组,以便用户可以更好的管理他们。当同组的通知有多条的时候,会自动折叠起来,避免通知比较多的时候,通知界面比较杂乱,例如当通知栏里有聊天消息通知和商品推荐通知时,我们只需要通过设置字段groupName,就可以对通知进行分组,给groupName设置不同的值可以将通知分为不同的组。
let notifyId = 0;
let chatRequest: notificationManager.NotificationRequest = {
id: notifyId++,
groupName:'ChatGroup',
content: {
//...
}
};
let productRequest: notificationManager.NotificationRequest = {
id: notifyId++,
groupName: 'ProductGroup',
content: {
//...
}
};
为通知添加行为意图
WantAgent提供了封装行为意图的能力,这里所说的行为意图主要是指拉起指定的应用组件及发布公共事件等能力。给通知添加行为意图后,点击通知后可以拉起指定的UIAbility或者发布公共事件,您可以按照以下步骤来实现:
创建WantAgentInfo信息。
场景一:拉起UIAbility。
let wantAgentInfo = {
wants: [
{
bundleName: "com.example.notification",
abilityName: "EntryAbility"
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 100
}
场景二:发布公共事件。
let wantAgentInfo = {
wants: [
{
action: 'event_name', // 设置事件名
parameters: {},
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 100,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
}
构造NotificationRequest对象。
let notificationRequest: notificationManager.NotificationRequest = {
id: 1,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "通知标题",
text: "通知内容"
}
},
wantAgent: wantAgentObj
};
发布WantAgent通知。
notificationManager.publish(notificationRequest).then(() => { // 发布通知
console.info("publish success");
}).catch((err: Error) => {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
});
用户通过点击通知栏上的通知,即可触发WantAgent的动作。
创建定时任务
在整个流程中,应用仅需:
使用reminderAgentManager模块的ReminderRequest类定义提醒实例;
使用reminderAgentManager模块的publishReminder接口发布提醒。
无需关注计时和通知发布等功能如何实现。
注意: 若是删除提醒流程,需要使用reminderAgentManager模块的cancelReminder接口取消提醒;若是修改提醒流程,则需要先删除旧的提醒,再新增新的提醒。
给你的应用添加提醒
实现提醒功能有以下前置条件:
- 添加后台代理提醒使用权限。
"module": {
// ...
"requestPermissions": [
{
"name": "ohos.permission.PUBLISH_AGENT_REMINDER"
}
]
}
- 导入后台代理提醒reminderAgentManager模块,将此模块命名为reminderAgentManager。
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
新增提醒
- 用reminderAgent.ReminderRequest类定义提醒实例。
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
// ...
export class ReminderService {
public addReminder(alarmItem: ReminderItem, callback?: (reminderId: number) => void) {
let reminder = this.initReminder(alarmItem);
reminderAgentManager.publishReminder(reminder, (err, reminderId) => {
if (callback != null) {
callback(reminderId);
}
});
}
private initReminder(item: ReminderItem): reminderAgentManager.ReminderRequestAlarm {
return {
reminderType: item.remindType,
hour: item.hour,
minute: item.minute,
daysOfWeek: item.repeatDays,
title: item.name,
ringDuration: item.duration * CommonConstants.DEFAULT_TOTAL_MINUTE,
snoozeTimes: item.intervalTimes,
timeInterval: item.intervalMinute * CommonConstants.DEFAULT_TOTAL_MINUTE,
actionButton: [
{
title: '关闭',
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
},
// ...
],
wantAgent: {
pkgName: CommonConstants.BUNDLE_NAME,
abilityName: CommonConstants.ABILITY_NAME
},
notificationId: item.notificationId,
// ...
}
}
// ...
}
- 发布提醒。
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
// ...
export class ReminderService {
public addReminder(alarmItem: ReminderItem, callback?: (reminderId: number) => void) {
let reminder = this.initReminder(alarmItem);
reminderAgentManager.publishReminder(reminder, (err, reminderId) => {
if (callback != null) {
callback(reminderId);
}
});
}
private initReminder(item: ReminderItem): reminderAgentManager.ReminderRequestAlarm {
// ...
}
// ...
}
如果需要删除提醒,可以调用cancelReminder()接口实现。
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
// ...
export class ReminderService {
public deleteReminder(reminderId: number) {
reminderAgentManager.cancelReminder(reminderId);
}
// ...
}
如果需要修改提醒,则需要先进行旧提醒的删除,再新增新的提醒。
public async setAlarmRemind(alarmItem: AlarmItem) {
let index: number = await this.findAlarmWithId(alarmItem.id);
if (index !== CommonConstants.DEFAULT_NUMBER_NEGATIVE) {
this.reminderService.deleteReminder(alarmItem.id);
} else {
// ...
}
this.reminderService.addReminder(alarmItem, (newId: number) => {
alarmItem.id = newId;
// ...
})
}