鸿蒙HarmonyOS实战-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 发布通知。
cancel(id: number, label: string, callback: AsyncCallback): void 取消指定的通知。
cancelAll(callback: AsyncCallback): void; 取消所有该应用发布的通知。

☀️2.1.2 开发步骤

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

🌈2.1.2.1 普通文本类型
less 复制代码
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
  id: 1,
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
      title: 'test_title',
      text: 'test_text',
      additionalText: 'test_additionalText',
    }
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            NotificationManager.publish(notificationRequest, (err) => {
              if (err) {
                console.error(`[ANS] failed to publish, error[${err}]`);
                return;
              }
              console.info(`[ANS] publish success`);
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
🌈2.1.2.2 长文本类型通知
typescript 复制代码
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
  id: 1,
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 长文本类型通知
    longText: {
      title: 'test_title',
      text: 'test_text',
      additionalText: 'test_additionalText',
      longText: 'test_longText',
      briefText: 'test_briefText',
      expandedTitle: 'test_expandedTitle',
    }
  }
}
// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
  if (err) {
    console.error(`[ANS] failed to publish, error[${err}]`);
    return;
  }
  console.info(`[ANS] publish success`);
});
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
🌈2.1.2.3 多行文本类型通知
typescript 复制代码
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
  id: 1,
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
    multiLine: {
      title: 'test_title',
      text: 'test_text',
      briefText: 'test_briefText',
      longTitle: 'test_longTitle',
      lines: ['line_01', 'line_02', 'line_03', 'line_04'],
    }
  }
}

// 发布通知
NotificationManager.publish(notificationRequest, (err) => {
  if (err) {
    console.error(`[ANS] failed to publish, error[${err}]`);
    return;
  }
  console.info(`[ANS] publish success`);
});
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
🌈2.1.2.4 图片类型通知
typescript 复制代码
import NotificationManager from '@ohos.notificationManager';
import image from '@ohos.multimedia.image';
// 图片构造
const color = new ArrayBuffer(60000);
let bufferArr = new Uint8Array(color);
for (var i = 0; i<bufferArr.byteLength;i++) {
  bufferArr[i++] = 60;
  bufferArr[i++] = 20;
  bufferArr[i++] = 220;
  bufferArr[i] = 100;
}
let opts = { editable:true, pixelFormat:"ARGB_8888", size: {height:100, width : 150}};

image
  // @ts-ignore
  .createPixelMap(color, opts)
  .then(async (pixelmap) => {
    await pixelmap.getImageInfo().then(imageInfo => {
      console.log("=====size: ====" + JSON.stringify(imageInfo.size));
    }).catch(err => {
      console.error("Failed to obtain the image pixel map information." + JSON.stringify(err));
      return;
    })
    let notificationRequest = {
      id: 1,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
        picture: {
          title: 'test_title',
          text: 'test_text',
          additionalText: 'test_additionalText',
          picture: pixelmap,
          briefText: 'test_briefText',
          expandedTitle: 'test_expandedTitle',
        }
      },
    }
    // 发送通知
    NotificationManager.publish(notificationRequest, (err) => {
      if (err) {
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
      }
      console.info(`[ANS] publish success `);
    });
  }).catch(err=>{
    console.error('create pixelmap failed =========='+ JSON.stringify(err));
    return;
  })

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

🦋2.2 发布进度条类型通知

☀️2.2.1 接口说明

接口名 描述
isSupportTemplate(templateName: string, callback: AsyncCallback): void 查询模板是否存在。

☀️2.2.2 开发步骤

less 复制代码
import NotificationManager from '@ohos.notificationManager';
NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {
  console.info(`[ANS] isSupportTemplate success`);
  let isSupportTpl: boolean = data; // isSupportTpl的值为true表示支持支持downloadTemplate模板类通知,false表示不支持
  // ...
}).catch((err) => {
  console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});

let template = {
  name:'downloadTemplate',
  data: {
    title: '标题:',
    fileName: 'music.mp4',
    progressValue: 30,
    progressMaxValue:100,
  }
}
//构造NotificationRequest对象
let notificationRquest = {
  id: 1,
  slotType: NotificationManager.SlotType.OTHER_TYPES,
  template: template,
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
      title: template.data.title + template.data.fileName,
      text: "sendTemplate",
      additionalText: "30%"
    }
  },
  deliveryTime: new Date().getTime(),
  showDeliveryTime: true
}
NotificationManager.publish(notificationRquest).then(() => {
  console.info(`[ANS] publish success `);
}).catch((err) => {
  console.error(`[ANS] failed to publish, error[${err}]`);
});

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

🦋2.3 为通知添加行为意图

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

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

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

☀️2.3.1 接口说明

接口名 描述
getWantAgent(info: WantAgentInfo, callback: AsyncCallback): void 创建WantAgent。
trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback): void 触发WantAgent意图。
cancel(agent: WantAgent, callback: AsyncCallback): void 取消WantAgent。
getWant(agent: WantAgent, callback: AsyncCallback): void 获取WantAgent的want。
equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback): void 判断两个WantAgent实例是否相等。

☀️2.3.2 开发步骤

less 复制代码
import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';

let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。

// 通过WantAgentInfo的operationType设置动作类型。
let wantAgentInfo = {
  wants: [
    {
      deviceId: '',
      bundleName: 'com.example.test',
      abilityName: 'com.example.test.MainAbility',
      action: '',
      entities: [],
      uri: '',
      parameters: {}
    }
  ],
  operationType: wantAgent.OperationType.START_ABILITY,
  requestCode: 0,
  wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}

// // wantAgentInfo
// let wantAgentInfo = {
//   wants: [
//     {
//       action: 'event_name', // 设置事件名。
//       parameters: {},
//     }
//   ],
//   operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
//   requestCode: 0,
//   wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
// }

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
  if (err) {
    console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
  } else {
    console.info('[WantAgent]getWantAgent success');
    wantAgentObj = data;
  }
});
// 构造NotificationRequest对象
let notificationRequest = {
  content: {
    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
      title: 'Test_Title',
      text: 'Test_Text',
      additionalText: 'Test_AdditionalText',
    },
  },
  id: 1,
  label: 'TEST',
  //wantAgent: wantAgentObj,//好像报错
}
// 通知发送
NotificationManager.publish(notificationRequest, (err) => {
  if (err) {
    console.error(`[ANS] failed to publish, error[${err}]`);
    return;
  }
  console.info(`[ANS] publish success `);
});

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

🚀写在最后

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
  • 想要获取最新鸿蒙学习资料,请点击→全套鸿蒙HarmonyOS学习资料
相关推荐
白茶三许6 小时前
【江鸟中原】“策无忧” 决策模型纯血鸿蒙项目开发
华为·harmonyos
2501_937189237 小时前
2025 优化版神马影视 8.8 源码系统|零基础部署
android·源码·开源软件·源代码管理·机顶盒
马剑威(威哥爱编程)7 小时前
【鸿蒙开发案例篇】鸿蒙跨设备实时滤镜同步的完整方案
华为·harmonyos
モンキー・D・小菜鸡儿9 小时前
Android Jetpack Compose 基础控件介绍
android·kotlin·android jetpack·compose
无风之翼9 小时前
android15 休眠唤醒过程中有时候屏幕显示时间一闪而过
android·锁屏
如此风景11 小时前
iOS SwiftUI开发所有修饰符使用详解
ios
mumuWorld11 小时前
KSCrash 实现机制深度分析
ios·源码阅读
方白羽11 小时前
Android全局悬浮拖拽视图
android·app·客户端
AskHarries12 小时前
Google 登录问题排查指南
flutter·ios·app
waeng_luo12 小时前
[鸿蒙2025领航者闯关] HarmonyOS深色模式实现
harmonyos·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结