0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看威廉希尔官方网站 视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

OpenHarmony开发案例:【自定义通知】

jf_46214456 来源:jf_46214456 作者:jf_46214456 2024-04-15 15:58 次阅读

介绍

本示例使用[@ohos.notificationManager] 等接口,展示了如何初始化不同类型通知的通知内容以及通知的发布、取消及桌面角标的设置,通知类型包括基本类型、长文本类型、多行文本类型、图片类型、带按钮的通知、点击可跳转到应用的通知。

效果预览:

image.png

使用说明

1.启动应用后,弹出是否允许发送通知的弹窗,点击允许后开始操作;

2.点击界面中对应的按钮发布不同类型的通知,下拉状态栏,在通知栏可以看到发布的通知;

3.打开提示音和震动效果开关后,再点击对应按钮发布不同类型的通知,在通知的同时会伴有提示音或震动效果;

4.点击消息列表Tab页,可以查看到刚才发送的消息,消息右边会显示数量,点击相应的消息可进行消息读取,取消相应通知;

5.回到仿桌面,可以看到角标数量,对应消息数量(使用前需安装并启动[仿桌面应用]);

6.点击取消所有通知,可以取消本应用发布的所有通知;

代码解读

鸿蒙开发文档参考了:[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]

entry/src/main/ets/
|---Application
|---components
|   |---NotificationList.ets                 //通知列表控件
|   |---NotificationPublish.ets              //通知发送控件
|   |---TitleBar.ets                         //标题控件
|---feature
|   |---NotificationOperations.ets           // 对外提供发布通知的接口
|---MainAbility
|---pages
|   |---Index.ets                            // 首页
entry/src/ohosTest/ets/
|---test
|   |---Index.test.ets                       // 首页的自动化测试    
notification/src/main/ets/
|---notification
|   |---NotificationContentUtil.ets          // 封装各种通知的主体内容
|   |---NotificationManagementUtil.ets       // 封装消息列表,角标设置的接口
|   |---NotificationRequestUtil.ets          // 接收通知的主体内容,返回完整的通知
|   |---NotificationUtil.ets                 // 封装允许发布通知、发布通知、关闭通知的接口
|   |---WantAgentUtil.ets                    // 封装wantAgent
|---util                                     // 日志文件```

### 具体实现

![搜狗高速浏览器截图20240326151450.png](//file1.elecfans.com/web2/M00/C5/D1/wKgZomYChGOAUaiiAADe1d8SeRY102.jpg)

* 允许发送通知、发送通知、取消通知的功能接口封装在NotificationUtil,源码参考:[NotificationUtil.ets]

/*

  • Copyright (c) 2023 Huawei Device Co., Ltd.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/

import notification from '@ohos.notificationManager'

import { logger } from '../util/Logger'

import { notificationManagement } from '../notification/NotificationManagementUtil';

const TAG: string = 'NotificationUtil'

class NotificationUtil {

private isPromptTone: boolean = false;

private isVibrationEffect: boolean = false;

promptTone(flag: boolean = this.isPromptTone): boolean {

this.isPromptTone = flag;

return this.isPromptTone;

}

vibrationEffect(flag: boolean = this.isVibrationEffect): boolean {

this.isVibrationEffect = flag;

return this.isVibrationEffect;

}

/**

  • enable notification

*/

async enableNotification() {

try {

  await notification.requestEnableNotification();

  logger.info(TAG, `enableNotification success`);

} catch (err) {

  logger.info(TAG, `enableNotification err ${JSON.stringify(err)}`);

}

}

/**

  • @param notificationRequest
  • @param id, Support specifying notification id when publishing notifications

*/

async publishNotification(notificationRequest: notification.NotificationRequest, id?: number) {

if (id && id > 0) {

  notificationRequest.id = id;

}

try {

  let notificationSlot: notification.NotificationSlot = {

    type: notification.SlotType.CONTENT_INFORMATION,

    level: notification.SlotLevel.LEVEL_DEFAULT

  };

  if (this.isPromptTone) {

    notificationSlot.sound = 'file:///system/etc/capture.ogg';

  }

  if (this.isVibrationEffect) {

    notificationSlot.vibrationEnabled = true;

    notificationSlot.vibrationValues = [200];

  }

  await notification.removeAllSlots();

  await notification.addSlot(notificationSlot.type);

  await notification.publish(notificationRequest);

  // 通知管理器添加新通知

  await notificationManagement.addNotification(notificationRequest);

  logger.info(TAG, `publish notification success, ${notificationRequest}`);

} catch (err) {

  if (err) {

    logger.error(TAG, `publishNotification err ${JSON.stringify(err)}`);

  }

}

}

/**

  • cancel notification by id

*/

async cancelNotificationById(id: number) {

try {

  await notification.cancel(id);

  logger.info(TAG, `cancel success`);

} catch (err) {

  if (err) {

    logger.info(TAG, `cancel err ${JSON.stringify(err)}`);

  }

}

}

/**

  • cancel all notification

*/

async cancelAllNotifications() {

try {

  await notification.cancelAll();

  logger.info(TAG, `cancel all success`);

} catch (err) {

  if (err) {

    logger.info(TAG, `cancel all err ${JSON.stringify(err)}`);

  }

}

}

}

export let notificationUtil = new NotificationUtil();

* 允许发送通知:在进入[Index.ets]前 通过notificationUtil.enableNotification()调用notification.requestEnableNotification()接口向用户请求发送通知;
* 发送通知:通过publishNotification()封装发布通知的接口;
* 取消通知:在[Index.ets]页面中通过点击事件调用cancelAllNotifications()取消所有的通知或者通过cancelNotificationById()取消指定id的通知;
* 获取应用所有消息通知、取消相关类型通知,角标管理接口封装在NotificationManagementUtil,源码参考:[NotificationManagementUtil.ets]

/*

  • Copyright (c) 2023 Huawei Device Co., Ltd.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/

import image from '@ohos.multimedia.image';

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

const BUNDLE_NAME: string = 'ohos.samples.customnotification';

const ABILITY_NAME: string = 'MainAbility';

const MULTI_LINE_CONTENT: Array< string > = ['line0', 'line1', 'line2', 'line3']; // 多行文本通知的多行文本内容

const enum NOTIFICATION_ID { // 定义不同类型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函数初始化基本通知类型的参数

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

let notificationText = this.context.resourceManager.getStringSync($r('app.string.notification_content'));

let notificationAdditional = this.context.resourceManager.getStringSync($r('app.string.notification_additional'));

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 发布基本类型通知

publishBasicNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined) {

    logger.info(TAG, `publishBasicNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.basic_notification'));

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.BASIC);

  }

} catch (error) {

  logger.info(TAG, `publishBasicNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布长文本类型通知

publishLongTextNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishLongTextNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.long_text_notification'));

    let notificationLongText = this.context.resourceManager.getStringSync($r('app.string.notification_long_text'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationLongTextContent(this.basicContent, notificationLongText, notificationBriefText, notificationExpandedText);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.LONG_TEXT);

  }

} catch (error) {

  logger.info(TAG, `publishLongTextNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布多行文本类型通知

publishMultiLineNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishMultiLineNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.multiline_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationLongTitle = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationMultiLineContent(this.basicContent, notificationBriefText, notificationLongTitle, MULTI_LINE_CONTENT);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.MULTI_LINE);

  }

} catch (error) {

  logger.info(TAG, `publishMultiLineNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布图片类型通知

publishPictureNotification = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishPictureNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.picture_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let imageArray = await this.context.resourceManager.getMedia($r('app.media.notification_icon').id);

    let imageResource = image.createImageSource(imageArray.buffer);

    let picture = await imageResource.createPixelMap();

    let notificationContent = notificationContentUtil.initNotificationPictureContent(this.basicContent, notificationBriefText, notificationExpandedText, picture);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.PICTURE);

  }

} catch (error) {

  logger.info(TAG, `publishPictureNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布带按钮的通知

publishNotificationWithButtons = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishNotificationWithButtons`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.notification_with_buttons'));

    let actionButtons: notification.NotificationActionButton[] = [

      {

        title: this.context.resourceManager.getStringSync($r('app.string.first_button')),

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

        title: this.context.resourceManager.getStringSync($r('app.string.second_button')),

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initButtonNotificationRequest(notificationContent, actionButtons);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithButtons error, error = ${JSON.stringify(error)}`);

}

}

// 发布点击跳转到应用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.clickable_notification'));

    let notificationWantAgent = await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME);

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initWantAgentNotificationRequest(notificationContent, notificationWantAgent);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithWantAgent error, error = ${JSON.stringify(error)}`);

}

}

}

* 获取应用所有消息通知:在constructor() 构造函数中调用@ohos.notificationManager中的getActiveNotifications接口获取所有通知及相应类型通知数量,通过封装getAllNotifications() 对外提供接口获取当前消息及消息数量。
* 取消相关类型通知:通过cancelNotificationType()封装取消相关通知类型的接口;
* 角标管理接口:通过setBadgeNumber()封装设置应用角标数量的接口,通过getBadgeNumber()封装获取当前应用角标数量的接口。
* 添加一条通知:通过addNotification()封装接口添加一条通知到消息管理器,当发送通知的时候进行调用。
* NotificationOperations向外提供接口,在页面中调用它们来实现功能,源码参考:[NotificationOperations.ets]

/*

  • Copyright (c) 2023 Huawei Device Co., Ltd.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/

import image from '@ohos.multimedia.image';

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

const BUNDLE_NAME: string = 'ohos.samples.customnotification';

const ABILITY_NAME: string = 'MainAbility';

const MULTI_LINE_CONTENT: Array< string > = ['line0', 'line1', 'line2', 'line3']; // 多行文本通知的多行文本内容

const enum NOTIFICATION_ID { // 定义不同类型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函数初始化基本通知类型的参数

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

let notificationText = this.context.resourceManager.getStringSync($r('app.string.notification_content'));

let notificationAdditional = this.context.resourceManager.getStringSync($r('app.string.notification_additional'));

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 发布基本类型通知

publishBasicNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined) {

    logger.info(TAG, `publishBasicNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.basic_notification'));

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.BASIC);

  }

} catch (error) {

  logger.info(TAG, `publishBasicNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布长文本类型通知

publishLongTextNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishLongTextNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.long_text_notification'));

    let notificationLongText = this.context.resourceManager.getStringSync($r('app.string.notification_long_text'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationLongTextContent(this.basicContent, notificationLongText, notificationBriefText, notificationExpandedText);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.LONG_TEXT);

  }

} catch (error) {

  logger.info(TAG, `publishLongTextNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布多行文本类型通知

publishMultiLineNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishMultiLineNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.multiline_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationLongTitle = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationMultiLineContent(this.basicContent, notificationBriefText, notificationLongTitle, MULTI_LINE_CONTENT);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.MULTI_LINE);

  }

} catch (error) {

  logger.info(TAG, `publishMultiLineNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布图片类型通知

publishPictureNotification = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishPictureNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.picture_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let imageArray = await this.context.resourceManager.getMedia($r('app.media.notification_icon').id);

    let imageResource = image.createImageSource(imageArray.buffer);

    let picture = await imageResource.createPixelMap();

    let notificationContent = notificationContentUtil.initNotificationPictureContent(this.basicContent, notificationBriefText, notificationExpandedText, picture);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.PICTURE);

  }

} catch (error) {

  logger.info(TAG, `publishPictureNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布带按钮的通知

publishNotificationWithButtons = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishNotificationWithButtons`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.notification_with_buttons'));

    let actionButtons: notification.NotificationActionButton[] = [

      {

        title: this.context.resourceManager.getStringSync($r('app.string.first_button')),

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

        title: this.context.resourceManager.getStringSync($r('app.string.second_button')),

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initButtonNotificationRequest(notificationContent, actionButtons);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithButtons error, error = ${JSON.stringify(error)}`);

}

}

// 发布点击跳转到应用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.clickable_notification'));

    let notificationWantAgent = await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME);

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initWantAgentNotificationRequest(notificationContent, notificationWantAgent);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithWantAgent error, error = ${JSON.stringify(error)}`);

}

}

}

* 发布通知:在[Index.ets] 页面中通过点击事件调用NotificationOperations中封装的对应的方法,然后从NotificationContentUtil中获取对应的主体内容content, 将content传递给NotificationRequestUtil得到完整的发布信息,最后调用NotificationUtil.publishNotification()发布内容;
* 播放提示音、马达震动的功能在NotificationUtil调用发布通知的接口处进行判断是否开启,源码参考:[NotificationOperations.ets]

/*

  • Copyright (c) 2023 Huawei Device Co., Ltd.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

*/

import image from '@ohos.multimedia.image';

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

const BUNDLE_NAME: string = 'ohos.samples.customnotification';

const ABILITY_NAME: string = 'MainAbility';

const MULTI_LINE_CONTENT: Array< string > = ['line0', 'line1', 'line2', 'line3']; // 多行文本通知的多行文本内容

const enum NOTIFICATION_ID { // 定义不同类型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函数初始化基本通知类型的参数

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

let notificationText = this.context.resourceManager.getStringSync($r('app.string.notification_content'));

let notificationAdditional = this.context.resourceManager.getStringSync($r('app.string.notification_additional'));

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 发布基本类型通知

publishBasicNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined) {

    logger.info(TAG, `publishBasicNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.basic_notification'));

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.BASIC);

  }

} catch (error) {

  logger.info(TAG, `publishBasicNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布长文本类型通知

publishLongTextNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishLongTextNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.long_text_notification'));

    let notificationLongText = this.context.resourceManager.getStringSync($r('app.string.notification_long_text'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationLongTextContent(this.basicContent, notificationLongText, notificationBriefText, notificationExpandedText);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.LONG_TEXT);

  }

} catch (error) {

  logger.info(TAG, `publishLongTextNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布多行文本类型通知

publishMultiLineNotification = () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishMultiLineNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.multiline_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationLongTitle = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let notificationContent = notificationContentUtil.initNotificationMultiLineContent(this.basicContent, notificationBriefText, notificationLongTitle, MULTI_LINE_CONTENT);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.MULTI_LINE);

  }

} catch (error) {

  logger.info(TAG, `publishMultiLineNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布图片类型通知

publishPictureNotification = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishPictureNotification`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.picture_notification'));

    let notificationBriefText = this.context.resourceManager.getStringSync($r('app.string.notification_brief_text'));

    let notificationExpandedText = this.context.resourceManager.getStringSync($r('app.string.notification_expanded_title'));

    let imageArray = await this.context.resourceManager.getMedia($r('app.media.notification_icon').id);

    let imageResource = image.createImageSource(imageArray.buffer);

    let picture = await imageResource.createPixelMap();

    let notificationContent = notificationContentUtil.initNotificationPictureContent(this.basicContent, notificationBriefText, notificationExpandedText, picture);

    notificationUtil.publishNotification(notificationRequestUtil.initBasicNotificationRequest(notificationContent), NOTIFICATION_ID.PICTURE);

  }

} catch (error) {

  logger.info(TAG, `publishPictureNotification error, error = ${JSON.stringify(error)}`);

}

}

// 发布带按钮的通知

publishNotificationWithButtons = async () = > {

try {

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    logger.info(TAG, `publishNotificationWithButtons`);

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.notification_with_buttons'));

    let actionButtons: notification.NotificationActionButton[] = [

      {

        title: this.context.resourceManager.getStringSync($r('app.string.first_button')),

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

        title: this.context.resourceManager.getStringSync($r('app.string.second_button')),

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initButtonNotificationRequest(notificationContent, actionButtons);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithButtons error, error = ${JSON.stringify(error)}`);

}

}

// 发布点击跳转到应用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

  if (this.context !== undefined && this.context !== null && this.basicContent !== undefined && this.basicContent !== null) {

    this.basicContent.title = this.context.resourceManager.getStringSync($r('app.string.clickable_notification'));

    let notificationWantAgent = await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME);

    let notificationContent = notificationContentUtil.initBasicNotificationContent(this.basicContent);

    let notificationRequest = notificationRequestUtil.initWantAgentNotificationRequest(notificationContent, notificationWantAgent);

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

  logger.info(TAG, `publishNotificationWithWantAgent error, error = ${JSON.stringify(error)}`);

}

}

}

* 发布通知:在[Index.ets]通过publishNotification()封装发布通知的接口的同时,根据NotificationUtil类中对应变量的值判断是否开启了提示音或马达,若已开启,则执行对应代码段;
* 控制提示音或马达的开关:在[Index.ets]通过调用NotificationUtil类两个方法对NotificationUtil类中对应变量进行更改,开启为true,关闭为false;
* 自动化测试,对应用接口或系统接口进行单元测试,并且对基于UI操作进行UI自动化测试
* interwetten与威廉的赔率体系
点击:在Index.test.ets的beforeAll中调用startAbility()拉起应用并进入首页, 然后通过Driver的assertComponentExist、findComponent和findWindow等获取到对应组件的位置, 最后通过click()模拟出人工点击对应组件的效果;
* 模拟各种操作流程:在Index.test.ets 的每个it里面,按一定逻辑顺序排好点击组件的顺序,从而模拟出人为操作的过程,最终,所有的it组成了整一个应用的自动化测试。

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 鸿蒙
    +关注

    关注

    57

    文章

    2345

    浏览量

    42822
  • OpenHarmony
    +关注

    关注

    25

    文章

    3716

    浏览量

    16260
收藏 人收藏

    评论

    相关推荐

    Android端自定义铃声 MobPush对安卓端自定义铃声的教程

    如何为APP推送设置独特的通知铃声呢?本次带来的是MobPush对安卓端自定义铃声的教程,快来看看吧~
    的头像 发表于 10-21 15:34 1148次阅读
    Android端<b class='flag-5'>自定义</b>铃声 MobPush对安卓端<b class='flag-5'>自定义</b>铃声的教程

    HarmonyOS开发实例:【自定义Emitter】

    使用[Emitter]实现事件的订阅和发布,使用[自定义弹窗]设置广告信息。
    的头像 发表于 04-14 11:37 995次阅读
    HarmonyOS<b class='flag-5'>开发</b>实例:【<b class='flag-5'>自定义</b>Emitter】

    HarmonyOS开发案例:【 自定义弹窗】

    基于ArkTS的声明式开发范式实现了三种不同的弹窗,第一种直接使用公共组件,后两种使用CustomDialogController实现自定义弹窗
    的头像 发表于 05-16 18:18 1354次阅读
    HarmonyOS<b class='flag-5'>开发案</b>例:【 <b class='flag-5'>自定义</b>弹窗】

    基于ArkTS语言的OpenHarmony APP应用开发自定义通知

    () } } 4、项目编译 4.1、打开项目 打开DevEco Studio,再打开自定义通知项目。 4.2、编译程序 点击菜单栏上的“Build” -> \"Rebuild
    发表于 09-14 15:12

    OpenHarmony应用开发自定义弹窗

    本文转载自《OpenHarmony应用开发自定义弹窗》,作者:zhushangyuan_ ​ 应用场景 在应用的使用和开发中,弹窗是一个很常见的场景,
    发表于 09-06 14:40

    1602自定义字符

    1602液晶能够显示自定义字符,能够根据读者的具体情况显示自定义字符。
    发表于 01-20 15:43 1次下载

    怎么样去开发自定义应用程序?

    Atmel小贴士 如何开发自定义应用程序
    的头像 发表于 07-11 00:05 2359次阅读

    OpenHarmony自定义组件:ClearableInput和Keyboard

    组件介绍: 本示例包含了两个OpenHarmony自定义组件,一个是ClearableInput,另一个是Keyboard。 ClearableInput 定义了一个带清空图标的文本输入框
    发表于 03-18 15:21 1次下载
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定义</b>组件:ClearableInput和Keyboard

    OpenHarmony自定义组件FlowImageLayout

    组件介绍 本示例是OpenHarmony自定义组件FlowImageLayout。 用于将一个图片列表以瀑布流的形式显示出来。 调用方法
    发表于 03-21 10:17 3次下载
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定义</b>组件FlowImageLayout

    OpenHarmony自定义组件ProgressWithText

    组件介绍 本示例是OpenHarmony自定义组件ProgressWithText。 在原来进度条的上方加了一个文本框,动态显示当前进度并调整位置。 调用方法
    发表于 03-23 14:03 1次下载
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定义</b>组件ProgressWithText

    OpenHarmony自定义组件CircleProgress

    组件介绍 本示例是OpenHarmony自定义组件CircleProgress。 用于定义一个带文字的圆形进度条。 调用方法
    发表于 03-23 14:06 4次下载
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定义</b>组件CircleProgress

    自定义视图组件教程案例

    自定义组件 1.自定义组件-particles(粒子效果) 2.自定义组件- pulse(脉冲button效果) 3.自定义组件-progress(progress效果) 4.
    发表于 04-08 10:48 14次下载

    自定义算子开发

    一个完整的自定义算子应用过程包括注册算子、算子实现、含自定义算子模型转换和运行含自定义op模型四个阶段。在大多数情况下,您的模型应该可以通过使用hb_mapper工具完成转换并顺利部署到地平线芯片上……
    的头像 发表于 04-07 16:11 2795次阅读
    <b class='flag-5'>自定义</b>算子<b class='flag-5'>开发</b>

    labview超快自定义控件制作和普通自定义控件制作

    labview超快自定义控件制作和普通自定义控件制作
    发表于 08-21 10:32 13次下载

    鸿蒙ArkUI实例:【自定义组件】

    组件是 OpenHarmony 页面最小显示单元,一个页面可由多个组件组合而成,也可只由一个组件组合而成,这些组件可以是ArkUI开发框架自带系统组件,比如 `Text` 、 `Button` 等,也可以是自定义组件,本节笔者简
    的头像 发表于 04-08 10:17 632次阅读