HarmonyOS 鸿蒙Next notificationManager 普通文本通知点击事件,和点击通知后自动消失
HarmonyOS 鸿蒙Next notificationManager 普通文本通知点击事件,和点击通知后自动消失
import Notification from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
import { WantAgent } from '@ohos.app.ability.wantAgent';
import { BusinessError } from '@kit.BasicServicesKit';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct InputPage {
[@State](/user/State) message: string = 'Hello World';
notification(message:string) {
let wantAgentObj:WantAgent | undefined = undefined// 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。
// 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo:wantAgent.WantAgentInfo = {
wants: [
{
deviceId: '',
bundleName: 'com.example.application',
abilityName: 'EntryAbility',
action: '',
entities: [],
uri: '',
parameters: {}
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
};
// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err:BusinessError, data:WantAgent) => {
if (err) {
console.error(`Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Succeeded in getting want agent.');
wantAgentObj = data;
let notificationRequest: Notification.NotificationRequest = {
id: 1,
content: {
notificationContentType:Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "通知测试",
text: message,
}
},
notificationSlotType:Notification.SlotType.SOCIAL_COMMUNICATION,
wantAgent: wantAgentObj
}
Notification.requestEnableNotification().then(() => {
Notification.publish(notificationRequest).then(() =>{
console.log("发布成功")
}).catch((err: BusinessError) => {
console.error(`publish:${err}`)
})
}).catch((err: BusinessError) => {
console.error(`${err}`)
})
});
}
build() {
Column(){
Button('发布通知').onClick(() => {
this.notification("这是一个通知")
})
}
}
}
更多关于HarmonyOS 鸿蒙Next notificationManager 普通文本通知点击事件,和点击通知后自动消失的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙系统中,针对NotificationManager
的普通文本通知点击事件及点击后自动消失的处理,可以通过以下方式实现:
-
设置点击事件: 使用
Intent
来设置通知的点击事件。在创建通知时,通过Notification.Builder
的setClickPendingIntent
方法绑定一个PendingIntent
,该PendingIntent
指向一个具体的Activity
或BroadcastReceiver
来处理点击事件。 -
自动消失: 通知的自动消失行为通常由系统控制,但可以通过设置通知的优先级、类别等属性来间接影响。在HarmonyOS中,当通知被用户点击后,系统通常会默认将其移除。如果需要确保通知在用户点击后立即消失,可以在处理点击事件的
Activity
或BroadcastReceiver
中,通过NotificationManager
的cancel
方法手动取消该通知。
示例代码(简化):
Notification.Builder builder = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setClickPendingIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
在点击事件处理逻辑中调用notificationManager.cancel(notificationId);
以确保通知消失。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html