当前位置:   article > 正文

【HarmonyOS】消息通知场景的实现_notificationmanager推鸿蒙

notificationmanager推鸿蒙

            从今天开始,博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”,对于刚接触这项技术的小伙伴在学习鸿蒙开发之前,有必要先了解一下鸿蒙,从你的角度来讲,你认为什么是鸿蒙呢?它出现的意义又是什么?鸿蒙仅仅是一个手机操作系统吗?它的出现能够和Android和IOS三分天下吗?它未来的潜力能否制霸整个手机市场呢?

抱着这样的疑问和对鸿蒙开发的好奇,让我们开始今天对消息通知的掌握吧!

目录

基础通知

进度条通知

通知意图


基础通知

在harmonyos当中提供了各种不同功能的通知来满足我们不同的业务需求,接下来我们首先开始对基础通知它的场景和实现方式进行讲解。

应用可以通过通知接口发送通知消息,提醒用户关注应用中的变化,用户可以在通知栏查看和操作通知内容。以下是基础通知的操作步骤:

1)导入 notification 模块:

import notificationManager from '@ohos.notificationManager';

2)发布通知:

  1. // 构建通知请求
  2. let request: notificationManager.NotificationRequest = {
  3. id: 10,
  4. content: { // 通知内容:... }
  5. }
  6. // 发布通知
  7. notificationManager.publish(request)
  8. .then(() => console.log('发布通知成功'))
  9. .catch(reason => console.log('发布通知失败', JSON.stringify((reason))))

通知的类型主要有以下四种:

类型枚举说明
NOTIFICATION_CONTENT_BASIC_TEXT普通文本型
NOTIFICATION_CONTENT_LONG_TEXT长文本型
NOTIFICATION_CONTENT_MULTILINE多行文本型
NOTIFICATION_CONTENT_PICTURE图片型

3)取消通知:

  1. // 取消指定id的通知
  2. notificationManager.cancel(10)
  3. // 取消当前应用所有通知
  4. notificationManager.calcelAll()

接下来对基础通知的四种通知类型进行简单的讲解,具体使用参数使用可在publish出悬停,然后点击查阅API参考进行查看:

这里将常用的参数 SlotType 进行简单讲解一下,其下面的具体参数可参考以下的表格:

类型枚举说明状态栏图标提示音横幅
SOCIAL_COMMUNICATION社交类型
SERVICE_INFORMATION服务类型
CONTENT_INFORMATION内容类型
OTHER_TYPES其他

关于通知的消息需要在手机模拟器上才能显示,在本地预览器中是不能显示的:  

  1. import notify from '@ohos.notificationManager'
  2. import image from '@ohos.multimedia.image'
  3. import { Header } from '../common/components/CommonComponents'
  4. @Entry
  5. @Component
  6. struct NotificationPage {
  7. // 全局任务id
  8. idx: number = 100
  9. // 图象
  10. pixel: PixelMap
  11. async aboutToAppear() {
  12. // 获取资源管理器
  13. let rm = getContext(this).resourceManager;
  14. // 读取图片
  15. let file = await rm.getMediaContent($r('app.media.watchGT4'))
  16. // 创建PixelMap
  17. image.createImageSource(file.buffer).createPixelMap()
  18. .then(value => this.pixel = value)
  19. .catch(reason => console.log('testTag', '加载图片异常', JSON.stringify(reason)))
  20. }
  21. build() {
  22. Column({space: 20}) {
  23. Header({title: '通知功能'})
  24. Button(`发送normalText通知`)
  25. .onClick(() => this.publishNormalTextNotification())
  26. Button(`发送longText通知`)
  27. .onClick(() => this.publishLongTextNotification())
  28. Button(`发送multiLine通知`)
  29. .onClick(() => this.publishMultiLineNotification())
  30. Button(`发送Picture通知`)
  31. .onClick(() => this.publishPictureNotification())
  32. }
  33. .width('100%')
  34. .height('100%')
  35. .padding(5)
  36. .backgroundColor('#f1f2f3')
  37. }
  38. // 普通文本发送
  39. publishNormalTextNotification() {
  40. let request: notify.NotificationRequest = {
  41. id: this.idx++,
  42. content: {
  43. contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  44. normal: {
  45. title: '通知标题' + this.idx,
  46. text: '通知内容详情',
  47. additionalText: '通知附加内容'
  48. }
  49. },
  50. showDeliveryTime: true,
  51. deliveryTime: new Date().getTime(),
  52. groupName: 'wechat',
  53. slotType: notify.SlotType.SOCIAL_COMMUNICATION
  54. }
  55. this.publish(request)
  56. }
  57. // 长文本发送
  58. publishLongTextNotification() {
  59. let request: notify.NotificationRequest = {
  60. id: this.idx++,
  61. content: {
  62. contentType: notify.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,
  63. longText: {
  64. title: '通知标题' + this.idx,
  65. text: '通知内容详情',
  66. additionalText: '通知附加内容',
  67. longText: '通知中的长文本,我很长,我很长,我很长,我很长,我很长,我很长,我很长',
  68. briefText: '通知概要和总结',
  69. expandedTitle: '通知展开时的标题' + this.idx
  70. }
  71. }
  72. }
  73. this.publish(request)
  74. }
  75. // 多行文本发送
  76. publishMultiLineNotification() {
  77. let request: notify.NotificationRequest = {
  78. id: this.idx++,
  79. content: {
  80. contentType: notify.ContentType.NOTIFICATION_CONTENT_MULTILINE,
  81. multiLine: {
  82. title: '通知标题' + this.idx,
  83. text: '通知内容详情',
  84. additionalText: '通知附加内容',
  85. briefText: '通知概要和总结',
  86. longTitle: '展开时的标题,我很宽,我很宽,我很宽',
  87. lines: [
  88. '第一行',
  89. '第二行',
  90. '第三行',
  91. '第四行',
  92. ]
  93. }
  94. }
  95. }
  96. this.publish(request)
  97. }
  98. // 图片型文本发送
  99. publishPictureNotification() {
  100. let request: notify.NotificationRequest = {
  101. id: this.idx++,
  102. content: {
  103. contentType: notify.ContentType.NOTIFICATION_CONTENT_PICTURE,
  104. picture: {
  105. title: '通知标题' + this.idx,
  106. text: '通知内容详情',
  107. additionalText: '通知附加内容',
  108. briefText: '通知概要和总结',
  109. expandedTitle: '展开后标题' + this.idx,
  110. picture: this.pixel
  111. }
  112. }
  113. }
  114. this.publish(request)
  115. }
  116. private publish(request: notify.NotificationRequest) {
  117. notify.publish(request)
  118. .then(() => console.log('notify test', '发送通知成功'))
  119. .then(reason => console.log('notify test', '发送通知失败', JSON.stringify(reason)))
  120. }
  121. }

呈现的效果如下:

进度条通知

进度条通知会展示一个动态的进度条,主要用于文件下载,长任务处理的进度显示,下面是实现进度条的基本步骤:

1)判断当前系统是否支持进度条模板

  1. this.isSupport = await notify.isSupportTemplate('downloadTemplate')
  2. if(!this.isSupport) {
  3. return
  4. }

2)定义通知请求

  1. let template = {
  2. name: 'downloadTemplate', // 模板名称,必须是downloadTemplate
  3. data: {
  4. progressValue: this.progressValue, // 进度条当前进度
  5. progressMaxValue: this.progressMaxValue // 进度条的最大值
  6. }
  7. }
  8. let request: notify.NotificationRequest = {
  9. id: this.notificationId,
  10. template: template,
  11. wantAgent: this.wantAgentInstance,
  12. content: {
  13. contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  14. normal: {
  15. title: this.filename + ': ' + this.state,
  16. text: '',
  17. additionalText: this.progressValue + '%'
  18. }
  19. }
  20. }

接下来对进度条进行实现:

  1. import notify from '@ohos.notificationManager'
  2. import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
  3. import promptAction from '@ohos.promptAction'
  4. enum DownloadState {
  5. NOT_BEGIN = '未开始',
  6. DOWNLOADING = '下载中',
  7. PAUSE = '已暂停',
  8. FINISHED = '已完成',
  9. }
  10. @Component
  11. export default struct DownloadCard {
  12. // 下载进度
  13. @State progressValue: number = 0
  14. progressMaxValue: number = 100
  15. // 任务状态
  16. @State state: DownloadState = DownloadState.NOT_BEGIN
  17. // 下载的文件名
  18. filename: string = '圣诞星.mp4'
  19. // 模拟下载的任务的id
  20. taskId: number = -1
  21. // 通知id
  22. notificationId: number = 999
  23. isSupport: boolean = false
  24. async aboutToAppear(){
  25. // 判断当前系统是否支持进度条模板
  26. this.isSupport = await notify.isSupportTemplate('downloadTemplate')
  27. }
  28. build() {
  29. Row({ space: 10 }) {
  30. Image($r('app.media.ic_files_video')).width(50)
  31. Column({ space: 5 }) {
  32. Row() {
  33. Text(this.filename)
  34. Text(`${this.progressValue}%`).fontColor('#c1c2c1')
  35. }
  36. .width('100%')
  37. .justifyContent(FlexAlign.SpaceBetween)
  38. Progress({
  39. value: this.progressValue,
  40. total: this.progressMaxValue,
  41. })
  42. Row({ space: 5 }) {
  43. Text(`${(this.progressValue * 0.43).toFixed(2)}MB`)
  44. .fontSize(14).fontColor('#c1c2c1')
  45. Blank()
  46. if (this.state === DownloadState.NOT_BEGIN) {
  47. Button('开始').downloadButton()
  48. .onClick(() => this.download())
  49. } else if (this.state === DownloadState.DOWNLOADING) {
  50. Button('取消').downloadButton().backgroundColor('#d1d2d3')
  51. .onClick(() => this.cancel())
  52. Button('暂停').downloadButton()
  53. .onClick(() => this.pause())
  54. } else if (this.state === DownloadState.PAUSE) {
  55. Button('取消').downloadButton().backgroundColor('#d1d2d3')
  56. .onClick(() => this.cancel())
  57. Button('继续').downloadButton()
  58. .onClick(() => this.download())
  59. } else {
  60. Button('打开').downloadButton()
  61. .onClick(() => this.open())
  62. }
  63. }.width('100%')
  64. }
  65. .layoutWeight(1)
  66. }
  67. .width('100%')
  68. .borderRadius(20)
  69. .padding(15)
  70. .backgroundColor(Color.White)
  71. }
  72. cancel() {
  73. // 取消定时任务
  74. if(this.taskId > 0){
  75. clearInterval(this.taskId);
  76. this.taskId = -1
  77. }
  78. // 清理下载任务进度
  79. this.progressValue = 0
  80. // 标记任务状态:未开始
  81. this.state = DownloadState.NOT_BEGIN
  82. // 取消通知
  83. notify.cancel(this.notificationId)
  84. }
  85. download() {
  86. // 清理旧任务
  87. if(this.taskId > 0){
  88. clearInterval(this.taskId);
  89. }
  90. // 开启定时任务,模拟下载
  91. this.taskId = setInterval(() => {
  92. // 判断任务进度是否达到100
  93. if(this.progressValue >= 100){
  94. // 任务完成了,应该取消定时任务
  95. clearInterval(this.taskId)
  96. this.taskId = -1
  97. // 并且标记任务状态为已完成
  98. this.state = DownloadState.FINISHED
  99. // 发送通知
  100. this.publishDownloadNotification()
  101. return
  102. }
  103. // 模拟任务进度变更
  104. this.progressValue += 2
  105. // 发送通知
  106. this.publishDownloadNotification()
  107. }, 500)
  108. // 标记任务状态:下载中
  109. this.state = DownloadState.DOWNLOADING
  110. }
  111. pause() {
  112. // 取消定时任务
  113. if(this.taskId > 0){
  114. clearInterval(this.taskId);
  115. this.taskId = -1
  116. }
  117. // 标记任务状态:已暂停
  118. this.state = DownloadState.PAUSE
  119. // 发送通知
  120. this.publishDownloadNotification()
  121. }
  122. open() {
  123. promptAction.showToast({
  124. message: '功能未实现'
  125. })
  126. }
  127. publishDownloadNotification(){
  128. // 1.判断当前系统是否支持进度条模板
  129. if(!this.isSupport){
  130. // 当前系统不支持进度条模板
  131. return
  132. }
  133. // 2.准备进度条模板的参数
  134. let template = {
  135. name: 'downloadTemplate', // 模板名称,必须是downloadTemplate
  136. data: {
  137. progressValue: this.progressValue, // 进度条当前进度
  138. progressMaxValue: this.progressMaxValue // 进度条的最大值
  139. }
  140. }
  141. let request: notify.NotificationRequest = {
  142. id: this.notificationId,
  143. template: template,
  144. content: {
  145. contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  146. normal: {
  147. title: this.filename + ': ' + this.state,
  148. text: '',
  149. additionalText: this.progressValue + '%'
  150. }
  151. }
  152. }
  153. // 3.发送通知
  154. notify.publish(request)
  155. .then(() => console.log('test', '通知发送成功'))
  156. .catch(reason => console.log('test', '通知发送失败!', JSON.stringify(reason)))
  157. }
  158. }
  159. @Extend(Button) function downloadButton() {
  160. .width(75).height(28).fontSize(14)
  161. }

最终呈现的效果如下:

通知意图

我们可以给通知或者其中的按钮设置的行为意图(Want),从而实现拉起应用组件或发布公共事件的能力,下面是其实现的步骤:

  1. // 创建wantInfo信息
  2. let wantInfo: wantAgent.WantAgentInfo = {
  3. wants: [
  4. {
  5. deviceId: '', // 设备的id
  6. bundleName: 'com.example.myapplication', // 应用唯一标识
  7. abilityName: 'EntryAbility',
  8. action: '',
  9. entities: [],
  10. }
  11. ],
  12. requestCode: 0,
  13. operationType: wantAgent.OperationType.START_ABILITY,
  14. wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
  15. }
  16. // 创建wantAgent实例
  17. this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
  18. // 通知请求
  19. let request: notify.NotificationRequest = {
  20. id: this.notificationId,
  21. template: template,
  22. wantAgent: this.wantAgentInstance, // 设置通知意图
  23. content: {
  24. //
  25. }
  26. }

通过上面的案例,我们给下载的进度条添加通知意图,让其下载的通知点击后跳转到下载页面,其实现的代码如下:

  1. import notify from '@ohos.notificationManager'
  2. import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
  3. import promptAction from '@ohos.promptAction'
  4. enum DownloadState {
  5. NOT_BEGIN = '未开始',
  6. DOWNLOADING = '下载中',
  7. PAUSE = '已暂停',
  8. FINISHED = '已完成',
  9. }
  10. @Component
  11. export default struct DownloadCard {
  12. // 下载进度
  13. @State progressValue: number = 0
  14. progressMaxValue: number = 100
  15. // 任务状态
  16. @State state: DownloadState = DownloadState.NOT_BEGIN
  17. // 下载的文件名
  18. filename: string = '圣诞星.mp4'
  19. // 模拟下载的任务的id
  20. taskId: number = -1
  21. // 通知id
  22. notificationId: number = 999
  23. isSupport: boolean = false
  24. wantAgentInstance: WantAgent
  25. async aboutToAppear(){
  26. // 1.判断当前系统是否支持进度条模板
  27. this.isSupport = await notify.isSupportTemplate('downloadTemplate')
  28. // 2.创建拉取当前应用的行为意图
  29. // 2.1.创建wantInfo信息
  30. let wantInfo: wantAgent.WantAgentInfo = {
  31. wants: [
  32. {
  33. bundleName: 'com.example.myapplication',
  34. abilityName: 'EntryAbility',
  35. }
  36. ],
  37. requestCode: 0,
  38. operationType: wantAgent.OperationType.START_ABILITY,
  39. wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
  40. }
  41. // 2.2.创建wantAgent实例
  42. this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
  43. }
  44. build() {
  45. Row({ space: 10 }) {
  46. Image($r('app.media.ic_files_video')).width(50)
  47. Column({ space: 5 }) {
  48. Row() {
  49. Text(this.filename)
  50. Text(`${this.progressValue}%`).fontColor('#c1c2c1')
  51. }
  52. .width('100%')
  53. .justifyContent(FlexAlign.SpaceBetween)
  54. Progress({
  55. value: this.progressValue,
  56. total: this.progressMaxValue,
  57. })
  58. Row({ space: 5 }) {
  59. Text(`${(this.progressValue * 0.43).toFixed(2)}MB`)
  60. .fontSize(14).fontColor('#c1c2c1')
  61. Blank()
  62. if (this.state === DownloadState.NOT_BEGIN) {
  63. Button('开始').downloadButton()
  64. .onClick(() => this.download())
  65. } else if (this.state === DownloadState.DOWNLOADING) {
  66. Button('取消').downloadButton().backgroundColor('#d1d2d3')
  67. .onClick(() => this.cancel())
  68. Button('暂停').downloadButton()
  69. .onClick(() => this.pause())
  70. } else if (this.state === DownloadState.PAUSE) {
  71. Button('取消').downloadButton().backgroundColor('#d1d2d3')
  72. .onClick(() => this.cancel())
  73. Button('继续').downloadButton()
  74. .onClick(() => this.download())
  75. } else {
  76. Button('打开').downloadButton()
  77. .onClick(() => this.open())
  78. }
  79. }.width('100%')
  80. }
  81. .layoutWeight(1)
  82. }
  83. .width('100%')
  84. .borderRadius(20)
  85. .padding(15)
  86. .backgroundColor(Color.White)
  87. }
  88. cancel() {
  89. // 取消定时任务
  90. if(this.taskId > 0){
  91. clearInterval(this.taskId);
  92. this.taskId = -1
  93. }
  94. // 清理下载任务进度
  95. this.progressValue = 0
  96. // 标记任务状态:未开始
  97. this.state = DownloadState.NOT_BEGIN
  98. // 取消通知
  99. notify.cancel(this.notificationId)
  100. }
  101. download() {
  102. // 清理旧任务
  103. if(this.taskId > 0){
  104. clearInterval(this.taskId);
  105. }
  106. // 开启定时任务,模拟下载
  107. this.taskId = setInterval(() => {
  108. // 判断任务进度是否达到100
  109. if(this.progressValue >= 100){
  110. // 任务完成了,应该取消定时任务
  111. clearInterval(this.taskId)
  112. this.taskId = -1
  113. // 并且标记任务状态为已完成
  114. this.state = DownloadState.FINISHED
  115. // 发送通知
  116. this.publishDownloadNotification()
  117. return
  118. }
  119. // 模拟任务进度变更
  120. this.progressValue += 2
  121. // 发送通知
  122. this.publishDownloadNotification()
  123. }, 500)
  124. // 标记任务状态:下载中
  125. this.state = DownloadState.DOWNLOADING
  126. }
  127. pause() {
  128. // 取消定时任务
  129. if(this.taskId > 0){
  130. clearInterval(this.taskId);
  131. this.taskId = -1
  132. }
  133. // 标记任务状态:已暂停
  134. this.state = DownloadState.PAUSE
  135. // 发送通知
  136. this.publishDownloadNotification()
  137. }
  138. open() {
  139. promptAction.showToast({
  140. message: '功能未实现'
  141. })
  142. }
  143. publishDownloadNotification(){
  144. // 1.判断当前系统是否支持进度条模板
  145. if(!this.isSupport){
  146. // 当前系统不支持进度条模板
  147. return
  148. }
  149. // 2.准备进度条模板的参数
  150. let template = {
  151. name: 'downloadTemplate', // 模板名称,必须是downloadTemplate
  152. data: {
  153. progressValue: this.progressValue, // 进度条当前进度
  154. progressMaxValue: this.progressMaxValue // 进度条的最大值
  155. }
  156. }
  157. let request: notify.NotificationRequest = {
  158. id: this.notificationId,
  159. template: template,
  160. wantAgent: this.wantAgentInstance, // 设置通知意图
  161. content: {
  162. contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  163. normal: {
  164. title: this.filename + ': ' + this.state,
  165. text: '',
  166. additionalText: this.progressValue + '%'
  167. }
  168. }
  169. }
  170. // 3.发送通知
  171. notify.publish(request)
  172. .then(() => console.log('test', '通知发送成功'))
  173. .catch(reason => console.log('test', '通知发送失败!', JSON.stringify(reason)))
  174. }
  175. }
  176. @Extend(Button) function downloadButton() {
  177. .width(75).height(28).fontSize(14)
  178. }

呈现的效果如下:

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

闽ICP备14008679号