当前位置:   article > 正文

鸿蒙HarmonyOS实战- ArkTS语言基础类库(通知)_arkts 消息提示

arkts 消息提示

前言

移动应用中的通知是指应用程序发送给用户的一种提示或提醒消息。这些通知可以在用户设备的通知中心或状态栏中显示,以提醒用户有关应用程序的活动、事件或重要信息。

移动应用中的通知可以分为两种类型:本地通知和远程通知。

本地通知是由应用程序自身发起的通知,不需要连接到远程服务器。应用程序可以根据特定条件或事件触发本地通知,例如定时提醒、任务完成等。本地通知可以直接在设备上显示,即使应用程序未运行,用户也能收到通知。

远程通知是由远程服务器发送给应用程序的通知。应用程序需要与远程服务器建立连接,以接收和处理远程通知。远程通知可以用于各种目的,如推送新闻、推广促销活动、提醒用户更新等。

无论是本地通知还是远程通知,移动应用中的通知通常都具有以下特点:

  1. 可定制性:应用程序可以自定义通知的内容、标题、图标等,以便向用户提供个性化的体验。

  2. 交互性:通知可以包含操作按钮或链接,用户可以通过点击通知来执行特定的操作,如打开应用、查看详情等。

  3. 静默通知:某些通知可以以静默模式发送,即用户不会收到任何视觉或声音提示,但应用程序仍可以在后台处理通知。

  4. 优先级控制:应用程序可以为通知设置优先级,以便在设备上显示不同的通知样式或触发不同的提示音。

一、通知

1.通知概述

1.1 通知简介

HarmonyOS应用可以通过通知接口发送通知消息。开发者可以使用该接口发送各种类型的通知,包括普通通知、长文字通知、大图通知等。终端用户可以通过通知栏查看通知内容,并进行相应操作,比如点击通知来打开应用。

通过通知接口,开发者可以设置通知的标题、内容、图标、优先级等属性。可以通过设置点击通知后的跳转动作,实现点击通知打开应用的功能。此外,开发者还可以通过设置通知的声音、震动等效果,提升用户体验。

通知常见的使用场景:

  • 提醒用户有待办事项,如闹钟、日历事件等。

  • 通知用户设备的状态,如电量低、网络连接状态等。

  • 提醒用户有新的邮件、社交媒体消息等。

  • 显示其他应用的提醒、通知,如电话、音乐播放器、定时器等。

  • 显示系统级别的通知,如系统更新、权限请求等。

  • 提醒用户有新的软件更新、安全补丁等。

  • 通知用户有新的活动、促销等。

  • 提醒用户有新的天气预报、股票行情等。

  • 显示其他应用的报警、警报等紧急通知。

HarmonyOS通过Advanced Notification Service(ANS)为应用程序提供通知管理服务。ANS支持多种通知类型,包括基础类型通知和进度条类型通知。

基础类型通知是一种简单的通知样式,用于显示重要的文本信息或简短的通知内容。它可以包含标题、内容和图标,用户可以通过点击通知来执行相关操作。

进度条类型通知用于显示任务进度或下载进度等信息。它除了包含基础类型通知的内容外,还可以添加一个进度条,以便用户了解任务的进度情况。

1.2 通知业务流程

通知子系统是一个中间件,负责接收来自通知发送端的通知消息,并将这些消息分发给订阅端。它起到了消息调度和分发的作用,实现了发布-订阅模式。

通知发送端是产生通知消息的组件,可以是应用程序、系统模块等。它负责生成通知消息,并通过IPC通信机制将消息发送到通知子系统。

通知订阅端是接收通知消息的组件,可以是应用程序、监控工具等。它通过订阅通知子系统,接收特定类型的通知消息。

整个通知业务流程如下:

  1. 通知发送端生成一条通知消息,包括通知的类型、内容等。
  2. 通知发送端通过IPC通信机制将通知消息发送到通知子系统。
  3. 通知子系统接收到通知消息后,根据消息的类型和订阅端的订阅情况,将消息分发给相应的订阅端。
  4. 订阅端接收到通知消息后,进行相应的处理,比如展示通知内容、触发某些操作等。

通过通知子系统的中间件架构,可以实现高效的通知消息分发。通知发送端和订阅端之间解耦,可以独立开发和部署,提高了系统的可扩展性和可维护性。同时,通过订阅机制,订阅端可以选择性地接收感兴趣的通知消息,提高了系统的灵活性。
在这里插入图片描述

2.发布通知

2.1 发布基础类型通知

基础类型通知可以用来发送各种类型的通知,包括短信息、提示信息和广告推送等。它们可以包含普通文本、长文本、多行文本和图片等。

类型描述
NOTIFICATION_CONTENT_BASIC_TEXT普通文本类型。
NOTIFICATION_CONTENT_LONG_TEXT长文本类型。
NOTIFICATION_CONTENT_MULTILINE多行文本类型。
NOTIFICATION_CONTENT_PICTURE图片类型。

例如,你可以发送一条包含简短文字的通知来提醒用户某个事件即将发生,或者发送一条包含长文本的通知来提供详细的信息。此外,你还可以发送一条包含多行文本的通知,每行显示一条信息。如果需要显示图片,你可以发送一条包含图片的通知。基础类型通知非常灵活,可以根据具体需求来进行设置。

2.1.1 接口说明
接口名描述
publish(request: NotificationRequest, callback: AsyncCallback<void>): void发布通知。
cancel(id: number, label: string, callback: AsyncCallback<void>): void取消指定的通知。
cancelAll(callback: AsyncCallback<void>): void;取消所有该应用发布的通知。
2.1.2 开发步骤

在HarmonyOS中,NotificationRequest类是用于创建通知的一个重要类。通过NotificationRequest类,可以设置通知的各种属性,如标题、内容、图标、声音、震动等。

2.1.2.1 普通文本类型
  1. import NotificationManager from '@ohos.notificationManager';
  2. let notificationRequest = {
  3. id: 1,
  4. content: {
  5. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
  6. normal: {
  7. title: 'test_title',
  8. text: 'test_text',
  9. additionalText: 'test_additionalText',
  10. }
  11. }
  12. }
  13. @Entry
  14. @Component
  15. struct Index {
  16. @State message: string = 'Hello World'
  17. build() {
  18. Row() {
  19. Column() {
  20. Text(this.message)
  21. .fontSize(50)
  22. .fontWeight(FontWeight.Bold)
  23. .onClick(() => {
  24. NotificationManager.publish(notificationRequest, (err) => {
  25. if (err) {
  26. console.error(`[ANS] failed to publish, error[${err}]`);
  27. return;
  28. }
  29. console.info(`[ANS] publish success`);
  30. });
  31. })
  32. }
  33. .width('100%')
  34. }
  35. .height('100%')
  36. }
  37. }

在这里插入图片描述

2.1.2.2 长文本类型通知
  1. import NotificationManager from '@ohos.notificationManager';
  2. let notificationRequest = {
  3. id: 1,
  4. content: {
  5. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 长文本类型通知
  6. longText: {
  7. title: 'test_title',
  8. text: 'test_text',
  9. additionalText: 'test_additionalText',
  10. longText: 'test_longText',
  11. briefText: 'test_briefText',
  12. expandedTitle: 'test_expandedTitle',
  13. }
  14. }
  15. }
  16. // 发布通知
  17. NotificationManager.publish(notificationRequest, (err) => {
  18. if (err) {
  19. console.error(`[ANS] failed to publish, error[${err}]`);
  20. return;
  21. }
  22. console.info(`[ANS] publish success`);
  23. });
  24. @Entry
  25. @Component
  26. struct Index {
  27. @State message: string = 'Hello World'
  28. build() {
  29. Row() {
  30. Column() {
  31. Text(this.message)
  32. .fontSize(50)
  33. .fontWeight(FontWeight.Bold)
  34. .onClick(() => {
  35. })
  36. }
  37. .width('100%')
  38. }
  39. .height('100%')
  40. }
  41. }

在这里插入图片描述

2.1.2.3 多行文本类型通知
  1. import NotificationManager from '@ohos.notificationManager';
  2. let notificationRequest = {
  3. id: 1,
  4. content: {
  5. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
  6. multiLine: {
  7. title: 'test_title',
  8. text: 'test_text',
  9. briefText: 'test_briefText',
  10. longTitle: 'test_longTitle',
  11. lines: ['line_01', 'line_02', 'line_03', 'line_04'],
  12. }
  13. }
  14. }
  15. // 发布通知
  16. NotificationManager.publish(notificationRequest, (err) => {
  17. if (err) {
  18. console.error(`[ANS] failed to publish, error[${err}]`);
  19. return;
  20. }
  21. console.info(`[ANS] publish success`);
  22. });
  23. @Entry
  24. @Component
  25. struct Index {
  26. @State message: string = 'Hello World'
  27. build() {
  28. Row() {
  29. Column() {
  30. Text(this.message)
  31. .fontSize(50)
  32. .fontWeight(FontWeight.Bold)
  33. .onClick(() => {
  34. })
  35. }
  36. .width('100%')
  37. }
  38. .height('100%')
  39. }
  40. }

在这里插入图片描述

2.1.2.4 图片类型通知
  1. import NotificationManager from '@ohos.notificationManager';
  2. import image from '@ohos.multimedia.image';
  3. // 图片构造
  4. const color = new ArrayBuffer(60000);
  5. let bufferArr = new Uint8Array(color);
  6. for (var i = 0; i<bufferArr.byteLength;i++) {
  7. bufferArr[i++] = 60;
  8. bufferArr[i++] = 20;
  9. bufferArr[i++] = 220;
  10. bufferArr[i] = 100;
  11. }
  12. let opts = { editable:true, pixelFormat:"ARGB_8888", size: {height:100, width : 150}};
  13. image
  14. // @ts-ignore
  15. .createPixelMap(color, opts)
  16. .then(async (pixelmap) => {
  17. await pixelmap.getImageInfo().then(imageInfo => {
  18. console.log("=====size: ====" + JSON.stringify(imageInfo.size));
  19. }).catch(err => {
  20. console.error("Failed to obtain the image pixel map information." + JSON.stringify(err));
  21. return;
  22. })
  23. let notificationRequest = {
  24. id: 1,
  25. content: {
  26. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
  27. picture: {
  28. title: 'test_title',
  29. text: 'test_text',
  30. additionalText: 'test_additionalText',
  31. picture: pixelmap,
  32. briefText: 'test_briefText',
  33. expandedTitle: 'test_expandedTitle',
  34. }
  35. },
  36. }
  37. // 发送通知
  38. NotificationManager.publish(notificationRequest, (err) => {
  39. if (err) {
  40. console.error(`[ANS] failed to publish, error[${err}]`);
  41. return;
  42. }
  43. console.info(`[ANS] publish success `);
  44. });
  45. }).catch(err=>{
  46. console.error('create pixelmap failed =========='+ JSON.stringify(err));
  47. return;
  48. })
  49. @Entry
  50. @Component
  51. struct Index {
  52. @State message: string = 'Hello World'
  53. build() {
  54. Row() {
  55. Column() {
  56. Text(this.message)
  57. .fontSize(50)
  58. .fontWeight(FontWeight.Bold)
  59. .onClick(() => {
  60. })
  61. }
  62. .width('100%')
  63. }
  64. .height('100%')
  65. }
  66. }

在这里插入图片描述

2.2 发布进度条类型通知

☀️2.2.1 接口说明
接口名描述
isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void查询模板是否存在。
☀️2.2.2 开发步骤
  1. import NotificationManager from '@ohos.notificationManager';
  2. NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {
  3. console.info(`[ANS] isSupportTemplate success`);
  4. let isSupportTpl: boolean = data; // isSupportTpl的值为true表示支持支持downloadTemplate模板类通知,false表示不支持
  5. // ...
  6. }).catch((err) => {
  7. console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
  8. });
  9. let template = {
  10. name:'downloadTemplate',
  11. data: {
  12. title: '标题:',
  13. fileName: 'music.mp4',
  14. progressValue: 30,
  15. progressMaxValue:100,
  16. }
  17. }
  18. //构造NotificationRequest对象
  19. let notificationRquest = {
  20. id: 1,
  21. slotType: NotificationManager.SlotType.OTHER_TYPES,
  22. template: template,
  23. content: {
  24. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  25. normal: {
  26. title: template.data.title + template.data.fileName,
  27. text: "sendTemplate",
  28. additionalText: "30%"
  29. }
  30. },
  31. deliveryTime: new Date().getTime(),
  32. showDeliveryTime: true
  33. }
  34. NotificationManager.publish(notificationRquest).then(() => {
  35. console.info(`[ANS] publish success `);
  36. }).catch((err) => {
  37. console.error(`[ANS] failed to publish, error[${err}]`);
  38. });
  39. @Entry
  40. @Component
  41. struct Index {
  42. @State message: string = 'Hello World'
  43. build() {
  44. Row() {
  45. Column() {
  46. Text(this.message)
  47. .fontSize(50)
  48. .fontWeight(FontWeight.Bold)
  49. .onClick(() => {
  50. })
  51. }
  52. .width('100%')
  53. }
  54. .height('100%')
  55. }
  56. }

在这里插入图片描述

2.3 为通知添加行为意图

WantAgent是HarmonyOS提供的一种功能,它允许开发者封装行为意图。行为意图主要用于拉起指定的应用组件或发布公共事件等。在HarmonyOS中,我们可以通过通知的方式将WantAgent从发布方传递给接收方,从而在接收方触发WantAgent中指定的意图。

举个例子,假设有一个应用发布一个通知消息,通常希望用户能够通过点击通知栏来打开目标应用组件。为了实现这个目标,开发者可以将WantAgent封装到通知消息中。当系统接收到带有WantAgent的通知消息时,用户点击通知栏时会触发WantAgent中指定的意图,从而打开目标应用组件。

为了实现通知中的行为意图,应用需要向应用组件管理服务(AMS)申请WantAgent,并将其与其他通知信息一起发送给桌面。当用户在桌面通知栏上点击通知时,系统会触发WantAgent的动作,从而实现目标应用组件的打开。

在这里插入图片描述

☀️2.3.1 接口说明
接口名描述
getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void创建WantAgent。
trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void触发WantAgent意图。
cancel(agent: WantAgent, callback: AsyncCallback<void>): void取消WantAgent。
getWant(agent: WantAgent, callback: AsyncCallback<Want>): void获取WantAgent的want。
equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void判断两个WantAgent实例是否相等。
☀️2.3.2 开发步骤
  1. import NotificationManager from '@ohos.notificationManager';
  2. import wantAgent from '@ohos.app.ability.wantAgent';
  3. let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。
  4. // 通过WantAgentInfo的operationType设置动作类型。
  5. let wantAgentInfo = {
  6. wants: [
  7. {
  8. deviceId: '',
  9. bundleName: 'com.example.test',
  10. abilityName: 'com.example.test.MainAbility',
  11. action: '',
  12. entities: [],
  13. uri: '',
  14. parameters: {}
  15. }
  16. ],
  17. operationType: wantAgent.OperationType.START_ABILITY,
  18. requestCode: 0,
  19. wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
  20. }
  21. // // wantAgentInfo
  22. // let wantAgentInfo = {
  23. // wants: [
  24. // {
  25. // action: 'event_name', // 设置事件名。
  26. // parameters: {},
  27. // }
  28. // ],
  29. // operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
  30. // requestCode: 0,
  31. // wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
  32. // }
  33. // 创建WantAgent
  34. wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
  35. if (err) {
  36. console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
  37. } else {
  38. console.info('[WantAgent]getWantAgent success');
  39. wantAgentObj = data;
  40. }
  41. });
  42. // 构造NotificationRequest对象
  43. let notificationRequest = {
  44. content: {
  45. contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  46. normal: {
  47. title: 'Test_Title',
  48. text: 'Test_Text',
  49. additionalText: 'Test_AdditionalText',
  50. },
  51. },
  52. id: 1,
  53. label: 'TEST',
  54. //wantAgent: wantAgentObj,//好像报错
  55. }
  56. // 通知发送
  57. NotificationManager.publish(notificationRequest, (err) => {
  58. if (err) {
  59. console.error(`[ANS] failed to publish, error[${err}]`);
  60. return;
  61. }
  62. console.info(`[ANS] publish success `);
  63. });
  64. @Entry
  65. @Component
  66. struct Index {
  67. @State message: string = 'Hello World'
  68. build() {
  69. Row() {
  70. Column() {
  71. Text(this.message)
  72. .fontSize(50)
  73. .fontWeight(FontWeight.Bold)
  74. .onClick(() => {
  75. })
  76. }
  77. .width('100%')
  78. }
  79. .height('100%')
  80. }
  81. }

在这里插入图片描述

结尾

每天进步一点点、需要付出努力亿点点。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/195351
推荐阅读
相关标签
  

闽ICP备14008679号