实现在 HarmonyOS 应用中创建、发布和管理通知,并接收用户对通知的回复。
一、通知代码
添加 NotificationAbility.ets 文件,代码如下:
import notification from '@ohos.notification';
import commonEvent from '@ohos.commonevent';
import { BusinessError } from '@ohos.base';
import { PixelMap, ImageSource, DecodingOptions, PixelFormat, Size, Rect } from '@ohos.multimedia.image';
export default class NotificationAbility {
static NOTIFICATION_ID = 1001;
static COMMON_EVENT_ACTION = 'common.event.NOTIFICATION_ACTION';
// 发布文本通知
static publishTextNotification() {
let notificationContent = {
title: '文本通知',
text: '这是一条文本通知',
};
this.publishNotification(notificationContent);
}
// 发布图片通知
static async publishImageNotification() {
// 加载图片资源
let rawFileEntry = await globalThis.getResourceManager().getRawFileEntry('entry/resources/rawfile/icon.png');
let resource = await rawFileEntry.openRawFile();
let imageSource = ImageSource.create(resource);
let decodingOptions = new DecodingOptions();
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
let pixelMap = await imageSource.createPixelmap(decodingOptions);
let notificationContent = {
title: '图片通知',
image: pixelMap,
};
this.publishNotification(notificationContent);
}
// 发布通知
static publishNotification(content: any) {
let notificationRequest = {
content: content,
id: this.NOTIFICATION_ID,
};
// 设置点击通知的回调
notification.subscribeNotificationAction(this.NOTIFICATION_ID, (data) => {
console.log('Notification clicked:', data);
});
notification.publishNotification(notificationRequest).then(() => {
console.log('Notification published successfully');
}).catch((err: BusinessError) => {
console.error('Failed to publish notification:', err);
});
}
// 取消通知
static cancelNotification() {
notification.cancelNotification(this.NOTIFICATION_ID).then(() => {
console.log('Notification canceled successfully');
}).catch((err: BusinessError) => {
console.error('Failed to cancel notification:', err);
});
}
// 订阅通用事件,接收用户回复
static subscribeCommonEvent() {
let matchingSkills = new commonEvent.MatchingSkills();
matchingSkills.addEvent(this.COMMON_EVENT_ACTION);
let subscriber = commonEvent.createSubscriber(matchingSkills);
subscriber.onReceive = (eventData: commonEvent.CommonEventData) => {
let action = eventData.intent?.action;
if (action === this.COMMON_EVENT_ACTION) {
let reply = eventData.intent?.parameters.reply;
console.log('User reply:', reply);
}
};
commonEvent.subscribe(subscriber).then(() => {
console.log('Subscribed to common event successfully');
}).catch((err: BusinessError) => {
console.error('Failed to subscribe to common event:', err);
});
}
}
二、使用通知能力
新建页面 Index.ets,添加以下代码:
import { Page } from '@ohos.ace.page';
import NotificationAbility from '../NotificationAbility';
@Entry
@Component
struct Index {
build() {
Column() {
Button('发布文本通知')
.onClick(() => {
NotificationAbility.publishTextNotification();
})
Button('发布图片通知')
.onClick(() => {
NotificationAbility.publishImageNotification();
})
Button('取消通知')
.onClick(() => {
NotificationAbility.cancelNotification();
})
Button('订阅通用事件')
.onClick(() => {
NotificationAbility.subscribeCommonEvent();
})
}.width('100%').height('100%').justifyContent('center').alignItems('center')
}
}
运行相关页面,点击页面上的按钮,即可测试发布通知、取消通知和接收用户回复功能。