需要HarmonyOS鸿蒙Next事件&通知Demo示例源码
需要HarmonyOS鸿蒙Next事件&通知Demo示例源码 需要 事件&通知 demo示例源码
3 回复
HarmonyOS(鸿蒙Next)的事件和通知机制是开发中的重要部分,系统提供了丰富的事件和通知API供开发者使用。以下是一个简单的事件和通知Demo示例源码,展示如何监听事件和发送通知。
import { common, notification } from '@ohos.notification';
import { EventHub } from '@ohos.event';
// 创建EventHub实例
const eventHub = new EventHub();
// 监听自定义事件
eventHub.on('customEvent', (data) => {
console.log('Received custom event:', data);
});
// 触发自定义事件
eventHub.emit('customEvent', { message: 'Hello, HarmonyOS!' });
// 发送通知
let notificationRequest: notification.NotificationRequest = {
id: 1,
content: {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'HarmonyOS Notification',
text: 'This is a notification from HarmonyOS.',
},
},
};
notification.publish(notificationRequest)
.then(() => {
console.log('Notification published successfully');
})
.catch((err) => {
console.error('Failed to publish notification:', err);
});
该示例代码展示了如何使用EventHub
监听和触发自定义事件,以及如何使用@ohos.notification
模块发送通知。
以下是HarmonyOS鸿蒙Next中事件与通知的简单Demo示例源码:
// 事件处理
public class MyEventHandler extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
Button button = new Button(this);
button.setText("点击触发事件");
button.setClickedListener(component -> {
// 触发事件
triggerEvent("用户点击了按钮");
});
setUIContent(button);
}
private void triggerEvent(String eventMessage) {
HiLog.info(LABEL, "事件触发: " + eventMessage);
}
}
// 通知处理
public class MyNotificationHandler extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
Button button = new Button(this);
button.setText("发送通知");
button.setClickedListener(component -> {
// 发送通知
sendNotification("新通知", "这是一个测试通知");
});
setUIContent(button);
}
private void sendNotification(String title, String text) {
NotificationRequest request = new NotificationRequest(1001);
NotificationNormalContent content = new NotificationNormalContent();
content.setTitle(title).setText(text);
request.setContent(content);
NotificationHelper.publishNotification(request);
}
}
此示例展示了如何在HarmonyOS中处理事件和发送通知。