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

 

介绍

本示例使用[@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

  • 允许发送通知、发送通知、取消通知的功能接口封装在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自动化测试

  • 模拟点击:在Index.test.ets的beforeAll中调用startAbility()拉起应用并进入首页, 然后通过Driver的assertComponentExist、findComponent和findWindow等获取到对应组件的位置, 最后通过click()模拟出人工点击对应组件的效果;

  • 模拟各种操作流程:在Index.test.ets 的每个it里面,按一定逻辑顺序排好点击组件的顺序,从而模拟出人为操作的过程,最终,所有的it组成了整一个应用的自动化测试。

最后呢,很多开发朋友不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走很多弯路,节省没必要的麻烦。由两位前阿里高级研发工程师联合打造《鸿蒙NEXT星河版OpenHarmony开发文档》里面内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)技术知识点

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习路线图。

高清完整版请点击→《鸿蒙NEXT星河版开发学习文档》

针对鸿蒙成长路线打造的鸿蒙学习文档。话不多说,我们直接看详细资料鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,帮助大家在技术的道路上更进一步。

《鸿蒙 (OpenHarmony)开发学习视频》

图片

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

OpenHarmony北向、南向开发环境搭建

图片

《鸿蒙开发基础》

  1. ArkTS语言

  2. 安装DevEco Studio

  3. 运用你的第一个ArkTS应用

  4. ArkUI声明式UI开发

  5. .……

图片

《鸿蒙开发进阶》

  1. Stage模型入门

  2. 网络管理

  3. 数据管理

  4. 电话服务

  5. 分布式应用开发

  6. 通知与窗口管理

  7. 多媒体技术

  8. 安全技能

  9. 任务管理

  10. WebGL

  11. 国际化开发

  12. 应用测试

  13. DFX面向未来设计

  14. 鸿蒙系统移植和裁剪定制

  15. ……

图片

《鸿蒙开发实战》

  1. ArkTS实践

  2. UIAbility应用

  3. 网络案例

  4. ……

图片

 获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

总结

鸿蒙—作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发

并且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,未来将会支持 50 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/548575.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

✯✯✯宁波 IATF16949 认证:助力汽车企业迈向卓越✯✯✯

&#x1f308;&#x1f308;&#x1f308;宁波IATF16949认证&#xff1a;&#x1f49d;助力汽车企业迈向卓越&#x1f497; &#x1f575;️‍♂️宁波&#xff0c;这座繁华的&#x1f98a;港口城市&#xff0c;不仅以其&#x1f42f;独特的地理位置和丰富的&#x1f54a;️历史…

霍夫曼编码(含完整源码)

1.第一步 统计所有的字符【*】出现的频次并按频次进行从小到大的排序 2.第二步 进行权值的合并 3.第三步 编码 左0 右 1 huffman编码大致分为以下步骤&#xff1a; 统计所有字符出现的频次构建huffman树huffman树生成huffman编码将源文件压缩成huffman编码结构收到源文件之后…

JavaScript入门--数组

JavaScript入门--数组 前言数组的操作1、在数组的尾部添加元素2、删除数组尾部的元素&#xff0c;也就是最后一个元素3、删除头部第一个元素4、在数组的前面添加元素 小案例5、数组的翻转6、数组的排序7、数组的合并8、数组的切片 前言 JS中的数组类似于python中的列表&#x…

软件设计:UML 模型图总结

1. 相关链接 参考教程&#xff1a; https://sparxsystems.com/resources/tutorials/ https://sparxsystems.com/enterprise_architect_user_guide/15.2/model_domains/whatisuml.html Unified Modeling Language (UML) description, UML diagram examples, tutorials and r…

产品经理技术脑:怎么看懂接口文档

日常产品开发过程中&#xff0c;涉及前后端数据交互的时候&#xff0c;往往会离不开接口调用&#xff0c;尽管产品经理一般不需要写接口文档&#xff08;负责接口中间层产品经理除外&#xff09;&#xff0c;但对接口了解&#xff0c;对于需求沟通、需求传达还是很有帮助的。 …

集成电路测试学习

集成电路&#xff08;Integrated Circuit&#xff0c;IC&#xff09;整个设计流程包括&#xff1a;电路设计、晶圆制造、晶圆测试、IC封装、封装后测试。 IC测试目的&#xff1a;一、确认芯片是否满足产品手册上定义的规范&#xff1b;二、通过测试测量&#xff0c;确认芯片可以…

【艾体宝方案】智驾未来:高性能实时数据库,车企的数据分析变革!

近年来&#xff0c;汽车行业持续朝向互联互通以及自动化方向的演进&#xff0c;无论是在优化制造流程、提升车辆安全与性能&#xff0c;还是提供定制化客户体验方面&#xff0c;汽车行业的都未来牢牢根植于其有效处理和利用数据的能力。 一、汽车行业面临的挑战 &#xff08;…

Java(120):使用Java对TiDB数据库批量写入数据

使用Java对TiDB数据库批量写入数据 1、前言&#xff1a; 本次对TiDB数据库测试需要1w条数据&#xff0c;如果MySQL可用存储过程造数&#xff0c;结果发现TiDB用不了。只能想其他办法&#xff0c;一种是Java直接批量插入&#xff0c;一种是Jmeter插入。这里用的Java插入。 如果…

CANoe中关于NetworkHardwareConfiguration中的setup设置参数的详解

前提说明 本文是以VN1640A中的CAN_FD工程为例&#xff0c;为大家讲解。 1&#xff1a;首先打开相关配置 重点讲解红色框中的参数&#xff0c;其他参数该如何设置&#xff0c;请参考我另外一篇文章“关于CANoe硬件及接口的学习笔记&#xff08;VN1640A&#xff09;”或自行查阅…

js 写 视频轮播

html代码 <div class"test_box"> <div class"test"> <a href"#"> <div class"test_a_box"> <div class"test_a_mask"></div> <div class"test_a_layer"> <div cla…

偏微分方程算法之混合边界差分

目录 一、研究对象 二、差分格式 2.1 向前欧拉格式 1. 中心差商 1.1.1 理论推导 1.1.2 算例实现 2. x0处向前差商&#xff0c;x1处向后差商 1.2.1 理论推导 1.2.2 算例实现 2.2 Crank-Nicolson格式 2.2.1 理论推导 2.2.2 算例实现 一、研究对象 这里我们以混合边界…

高分一号卫星(GF-1):中国遥感科技的骄傲

高分一号卫星&#xff08;GF-1&#xff09;是中国遥感科技领域的一项突破性成就&#xff0c;其引入了先进的成像技术和灵活的数据获取模式&#xff0c;为中国的资源管理、环境监测和城市规划等领域带来了巨大的变革。本文将深入介绍高分一号卫星的技术参数、成像能力以及应用场…

抽奖系统设计

如何设计一个百万级用户的抽奖系统&#xff1f; - 掘金 如何设计百万人抽奖系统…… 在实现抽奖逻辑时&#xff0c;Redis 提供了多种数据结构&#xff0c;选择哪种数据结构取决于具体的抽奖规则和需求。以下是一些常见场景下推荐使用的Redis数据结构&#xff1a; 无序且唯一奖…

解析数据科学,探索ChatGPT背后的奥秘

在当今这个由数据驱动和AI蓬勃发展的时代&#xff0c;数据科学作为一门融合多种学科的综合性领域&#xff0c;对于推动各行各业实现数字化转型升级起着至关重要的作用。近年来&#xff0c;大语言模型技术发展态势强劲&#xff0c;为数据科学的进步做出了巨大贡献。其中&#xf…

第四百六十二回

文章目录 1. 概念介绍2. 实现方法3. 示例代码4. 内容总结 我们在上一章回中介绍了"关于MediaQuery的优化"相关的内容&#xff0c;本章回中将介绍readMore这个三方包.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1. 概念介绍 我们在本章回中介绍的readMore是一个…

新经济助推高质量发展“大有云钞”聚焦未来趋势

近日&#xff0c;由大有云钞科技&#xff08;北京&#xff09;有限公司主办的一场关于“新经济助力高质量发展法治研讨会”在北京国家会议中心隆重举行。此次研讨会汇聚了来自政府、企业、学术界和法律界的众多专家学者&#xff0c;共同探讨新经济背景下的法治建设和高质量发展…

Scrapy 框架基础

Scrapy框架基础Scrapy框架进阶 Scrapy 框架基础 【一】框架介绍 【1】简介 Scrapy是一个用于网络爬取的快速高级框架&#xff0c;使用Python编写他不仅可以用于数据挖掘&#xff0c;还可以用于检测和自动化测试等任务 【2】框架 官网链接https://docs.scrapy.org/en/late…

YesPMP平台 | 活动有礼,现金奖励点击领取!

YesPMP众包平台在线发福利啦&#xff0c;活动火热开启&#xff0c;现金奖励等你来领&#xff0c;最高可领千元&#xff0c;赶快参与将奖励收入囊中&#xff0c;一起来了解活动细节吧&#xff01; 一、活动内容&#xff1a; 活动一&#xff1a;【项目征集令】活动&#xff0c;…

二路归并排序的算法设计和复杂度分析(C语言)

目录 实验内容&#xff1a; 实验过程&#xff1a; 1.算法设计 2.程序清单 3.运行结果 4.算法复杂度分析 实验内容&#xff1a; 二路归并排序的算法设计和复杂度分析。 实验过程&#xff1a; 1.算法设计 二路归并排序算法&#xff0c;分为两个阶段&#xff0c;首先对待排…

Anaconda下的tensorflow安装

关于Anaconda的安装以及配置可以浏览我的上一篇博客Anaconda的安装与配置 下面是安装tensorflow的命令&#xff0c;使用下列指令安装前需要配置好CUDA&#xff0c;关于CUDA的配置在上一篇博客中有详细的步骤描述。 关于官方环境配置的要求可以浏览官网&#xff1a;https://t…