鸿蒙开发:应用通知栏基本操作

🎯 应用通知栏基本操作

⭐⭐⭐⭐

📌 见解

通知旨在让用户以合适的方式及时获得有用的新消息,帮助用户高效地处理任务。应用可以通过通知接口发送通知消息,用户可以通过通知栏查看通知内容,也可以点击通知来打开应用

🎬 使用场景

使用场景 特性描述 相关API/组件
服务与通讯通知 即时通讯、服务提醒(订单/出行/健康等),支持高优先级通知,允许触发铃声/振动 NotificationManager.SlotType.SOCIAL_COMMUNICATION NotificationRequest
资讯营销通知 内容推荐/促销信息,静默展示在通知栏,无声音提示,每日推送数量受限 默认slotType(非SOCIAL_COMMUNICATION)
进度条通知 实时显示任务进度(如文件下载/上传) 基于基础通知扩展实现 NotificationRequest中的progress参数
图片/多媒体通知 展示商品详情等含图片或富媒体内容的通知 NOTIFICATION_CONTENT_PICTURE image.PixelMapFormat.RGBA_8888
交互式通知 包含操作按钮(确认/取消),支持通知栏直接交互 NotificationActionButton
定时/代理提醒 闹钟、日程等需要精确时间触发的场景 reminderAgentManager模块 publishReminder
系统级通知 设备告警、系统更新等关键事件 系统预留通道(如SlotType.SERVICE_REMINDER

🧩 拆解

⚠️ 注意

  • 更新通知: 在发出通知后,使用您之前使用的相同通知ID,再次调用notificationManager.publish来实现通知的更新。如果之前的通知是关闭的,将会创建新通知

  • 移除通知:

  • 通过通知ID和通知标签取消已发布的通知,notificationManager.cancel(notificationId)

  • 取消所有已发布的通知,notificationManager.cancelAll()

🧱 普通文本类型通知

javascript 复制代码
// 1、获取用户授权才能发送通知。
windowStage.loadContent('pages/Index', (err) => {
  notificationManager.requestEnableNotification(this.context).then(() => {
      hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag',
          `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`)
    })
})

// 2、视图封装发送通知
pushTextNotification() {
// 设置发布通知的内容和相关配置信息
let notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    }
}
// 发布通知 当发布通知成功,err为undefined,否则为错误对象。
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 3、视图使用
Column() {
    // 文本
    Button('点击通知')
    .onClick(() => {
        this.pushTextNotification()
    })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)

🧱 发布进度类型通知

javascript 复制代码
@State isSupport: boolean = false

aboutToAppear(): void {
// 1、通过该接口查询是否支持对应的通知模板。
notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
    this.isSupport = isSupport
})
}
// 2、模拟下载发布通知
pushProgressNotification() {
if (!this.isSupport) return
setInterval(() => {
    const template: notificationManager.NotificationTemplate = {
    name: 'downloadTemplate',
    data: {
        title: '进度',
        fileName: '进度',
        progressValue: this.curProgress,
        progressMaxValue: 100,
        isProgressIndeterminate: false
    }
    };
    const notificationRequest: notificationManager.NotificationRequest = {
    id: 5,
    notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
    template: template,
    content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
        title: '进度',
        text: ' ',
        additionalText: `${this.curProgress}%`
        }
    },
    };

    // 发布通知
    notificationManager.publish(notificationRequest, (err: BusinessError) => {
    if (err) {
        return
    }
    })

    this.curProgress++
}, 1000)
}

🧱 添加意图以例1为case

javascript 复制代码
// 1、创建对于状态变量
@State wantAgentObj: WantAgent | undefined = undefined // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作
  private bundleName: string = this.context.abilityInfo.bundleName
  private abilityName: string = this.context.abilityInfo.name

// 2、创建wantAgent
createWantAgent() {
// 通过WantAgentInfo的operationType设置动作类型
const wantAgentInfo: wantAgent.WantAgentInfo = {
    wants: [
    {
        deviceId: '',
        bundleName: this.bundleName, // 需要替换为对应的bundleName。
        abilityName: this.abilityName, // 需要替换为对应的abilityName。
        action: '',
        entities: [],
        uri: '',
        parameters: {}
    }
    ],
    actionType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
}

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
    if (err) {
       return;
    }
    this.wantAgentObj = data
})
}

// 3、创天通知栏并且携带wantAgent
pushTextNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

🧱 通知组(将不同类型的通知分为不同的组,以便用户可以更好的管理他们。)

javascript 复制代码
// 1、创建通知栏组1
 /**
   * 文本通知
   */
pushTextNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    groupName: 'textGroup', // 用于归纳的组别
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 2、创建组别2
/**
   * 组通知类型(文本2)
   */
pushTextGroupNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 110, // 通知ID
    groupName: 'textGroup',
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题组2',
        text: '通知内容详情组2'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 3、视图使用
// 通知组类型
Column() {
Text('通知组测试:')
    .fontSize(20)
    .fontWeight(FontWeight.Bold)
Row({ space: 20 }) {
    Button('文本组1')
    .onClick(() => {
        this.pushTextNotification()
    })

    Button('文本组2')
    .onClick(() => {
        this.pushTextGroupNotification()
    })
}
}

🔥🔥🔥 完整代码*

javascript 复制代码
// 1、用户授权src/main/ets/entryability/EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

windowStage.loadContent('pages/Index', (err) => {
    if (err.code) {
    hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
    return;
    }
    hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    // TODO: 在这里授权
    notificationManager.requestEnableNotification(this.context).then(() => {
    hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
    }).catch((err: BusinessError) => {
    hilog.error(0x0000, 'testTag',
        `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
    });
});
}

// 2、构建视图 src/main/ets/pages/Index.ets
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common, wantAgent, WantAgent } from '@kit.AbilityKit';

@Entry
@Component
struct NotificationCase {
  private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext
  @State curProgress: number = 0
  @State isSupport: boolean = false
  @State wantAgentObj: WantAgent | undefined = undefined // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作
  private bundleName: string = this.context.abilityInfo.bundleName
  private abilityName: string = this.context.abilityInfo.name

  aboutToAppear(): void {
    // 通过该接口查询是否支持对应的通知模板。
    notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
      this.isSupport = isSupport
    })

    this.createWantAgent()
  }

  aboutToDisappear(): void {
    notificationManager.cancelAll()
  }

  /**
   * wantAgent创建
   */
  createWantAgent() {
    // 通过WantAgentInfo的operationType设置动作类型
    const wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: this.bundleName, // 需要替换为对应的bundleName。
          abilityName: this.abilityName, // 需要替换为对应的abilityName。
          action: '',
          entities: [],
          uri: '',
          parameters: {}
        }
      ],
      actionType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    }

    // 创建WantAgent
    wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
      if (err) {
        return;
      }
      this.wantAgentObj = data
    })
  }

  /**
   * 文本通知
   */
  pushTextNotification() {
    const notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 1, // 通知ID
      groupName: 'textGroup',
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '通知内容标题',
          text: '通知内容详情'
        }
      },
      wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
      tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
    }
    notificationManager.publish(notificationRequest).then(() => { // 发布通知
      console.info('publish success');
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }

  /**
   * 进度条通知
   */
  pushProgressNotification() {
    if (!this.isSupport) {
      return
    }
    setInterval(() => {
      const template: notificationManager.NotificationTemplate = {
        name: 'downloadTemplate',
        data: {
          title: '进度',
          fileName: '进度',
          progressValue: this.curProgress,
        }
      };
      const notificationRequest: notificationManager.NotificationRequest = {
        id: 5,
        notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
        template: template,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: '进度',
            text: ' ',
            additionalText: `${this.curProgress}%`
          }
        },
        wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
        tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
      };

      // 发布通知
      notificationManager.publish(notificationRequest, (err: BusinessError) => {
        if (err) {
          return
        }
      })

      this.curProgress++
    }, 1000)
  }

  /**
   * 组通知类型(文本2)
   */
  pushTextGroupNotification() {
    const notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 110, // 通知ID
      groupName: 'textGroup',
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '通知内容标题组2',
          text: '通知内容详情组2'
        }
      },
      wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
      tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
    }
    notificationManager.publish(notificationRequest).then(() => { // 发布通知
      console.info('publish success');
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }

  build() {
    Column({ space: 20 }) {

      Row({ space: 20 }) {
        Text('文本测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        // 文本通知
        Button('文本通知')
          .onClick(() => {
            this.pushTextNotification()
          })
      }

      Column() {
        Text('进度条测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)

        // 进度条通知
        Column({ space: 20 }) {
          Button('进度条点击开始下载 (模拟)')
            .onClick(() => {
              this.pushProgressNotification()
            })
          Progress({ value: this.curProgress, total: 100, type: ProgressType.Linear })
        }
        .padding({ left: 20, right: 20 })
      }


      // 通知组类型
      Column() {
        Text('通知组测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        Row({ space: 20 }) {
          Button('文本组1')
            .onClick(() => {
              this.pushTextNotification()
            })

          Button('文本组2')
            .onClick(() => {
              this.pushTextGroupNotification()
            })
        }
      }

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

📝 通知会在不同场景以不同形式提示用户,例如通知在状态栏上显示为图标、在通知栏上会显示通知详细信息。重要的信息还可以使用横幅通知,浮动在界面顶部显示

🌸🌼🌺

相关推荐
一只栖枝9 小时前
HarmonyOS 开发高级认证是什么?含金量高吗?
华为·华为认证·harmonyos·鸿蒙·考证
夏文强15 小时前
HarmonyOS开发-数据管理-ArkData(3)- 关系型数据库
前端·数据库·harmonyos·鸿蒙
熊猫钓鱼>_>1 天前
从零到一:使用 ArkTS 构建你的第一个鸿蒙应用
华为·移动开发·harmonyos·arkts·鸿蒙·component·网页开发
Kisang.1 天前
【HarmonyOS】ArkWeb——从入门到入土
前端·华为·typescript·harmonyos·鸿蒙
Kisang.2 天前
【HarmonyOS】性能优化——组件的封装与复用
华为·性能优化·typescript·harmonyos·鸿蒙
Kisang.4 天前
【HarmonyOS】ArkTS的多线程并发(下)——线程间通信对象的传递
华为·typescript·harmonyos·鸿蒙
鸿蒙小白龙5 天前
OpenHarmony内核开发实战手册:编译构建、HCK框架与性能优化
harmonyos·鸿蒙·鸿蒙系统·open harmony
lqj_本人7 天前
EntryAbility继承FlutterAbility应用入口深度解析
鸿蒙
●VON7 天前
补充说明:Windows 完全可以开发 Qt 鸿蒙应用!(附专属适配方案)
windows·qt·华为·harmonyos·鸿蒙