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

news2024/11/29 14:55:01

 

介绍

本示例使用[@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 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

TensorFlow实战Google深度学习框架 PDF书籍分享

今天又来给大家推荐一本TensorFlow方面的书籍<TensorFlow实战Google深度学习框架>。本书适用于想要使用深度学习或TensorFlow的数据科学家、工程师&#xff0c;希望了解大数据平台工程师&#xff0c;对人工智能、深度学习感兴趣的计算机相关从业人员及在校学生等。 下载当…

【数据结构与算法】用两个栈实现一个队列

题目 用两个栈&#xff0c;实现一个队列功能 add delete length 队列 用数组可以实现队列&#xff0c;数组和队列的区别是&#xff1a;队列是逻辑结构是一个抽象模型&#xff0c;简单地可以用数组、链表实现&#xff0c;所以数组和链表是一个物理结构&#xff0c;队列是一个逻…

Cannot access ‘androidx.activity.FullyDrawnReporterOwner‘

Android Studio新建项目就报错&#xff1a; Cannot access ‘androidx.activity.FullyDrawnReporterOwner’ which is a supertype of ‘cn.dazhou.osddemo.MainActivity’. Check your module classpath for missing or conflicting dependencies 整个类都报错了。本来原来一直…

阿里面试:DDD中的实体、值对象有什么区别?

在领域驱动设计&#xff08;DDD&#xff09;中&#xff0c;有两个基础概念&#xff1a;实体&#xff08;Entity&#xff09;和值对象&#xff08;Value Object&#xff09;。 使用这些概念&#xff0c;我们可以把复杂的业务需求映射成简单、明确的数据模型。正确使用实体和值对…

【环境】原则

系列文章目录 【引论一】项目管理的意义 【引论二】项目管理的逻辑 【环境】概述 【环境】原则 一、培养项目系统性思维 1.1 系统性思维 1.2 系统性思维的价值 1.3 建模和推演&数字孪生 二、项目的复杂性和如何驾驭复杂性 2.1 复杂性的三个维度 2.2 如何驾驭复杂性 三、…

【御控物联】Java JSON结构转换(4):对象To对象——规则属性重组

文章目录 一、JSON结构转换是什么&#xff1f;二、术语解释三、案例之《JSON对象 To JSON对象》四、代码实现五、在线转换工具六、技术资料 一、JSON结构转换是什么&#xff1f; JSON结构转换指的是将一个JSON对象或JSON数组按照一定规则进行重组、筛选、映射或转换&#xff0…

谷歌pixel6/7pro等手机WiFi不能上网,显示网络连接受限

近期在项目中遇到一个机型出现的问题,先对项目代码进行排查,发现别的设备都能正常运行,就开始来排查机型的问题,特意写出来方便后续查看,也方便其它开发者来自查。 设备机型:Pixel 6a 设备安卓版本:13 该方法无需root,只需要电脑设备安装adb(即Android Debug Bridge…

GPT提示词分享 —— 解梦

&#x1f449; 对你描述的梦境进行解读。 我希望你能充当一个解梦者。我将给你描述我的梦&#xff0c;而你将根据梦中出现的符号和主题提供解释。不要提供关于梦者的个人意见或假设。只提供基于所给信息的事实性解释。 GPT3.5的回答 GPT3.5 &#x1f447; 感觉有点傻&#xf…

申请免费https证书

https证书是什么&#xff1a; https证书是指在http超文本传输协议的前提下安装部署了SSL/TLS证书后形成的全新协议&#xff0c;https安全超文本传输协议。在https证书部署完成后&#xff0c;服务器端和浏览器端进行的信息交互的过程中会有加密层保护&#xff0c;使得原本明文传…

群晖NAS安装Synology Office与Drive结合内网穿透实现本地文件公网分享与远程协作

文章目录 本教程解决的问题是&#xff1a;1. 本地环境配置2. 制作本地分享链接3. 制作公网访问链接4. 公网ip地址访问您的分享相册5. 制作固定公网访问链接 本教程解决的问题是&#xff1a; 1.Word&#xff0c;PPT&#xff0c;Excel等重要文件存在本地环境&#xff0c;如何在编…

【解决】Spring Boot创建项目常见问题

&#x1f3a5; 个人主页&#xff1a;Dikz12&#x1f525;个人专栏&#xff1a;Spring学习之路&#x1f4d5;格言&#xff1a;吾愚多不敏&#xff0c;而愿加学欢迎大家&#x1f44d;点赞✍评论⭐收藏 目录 idea无maven选项 无效发行版17 类⽂件具有错误的版本 61.0, 应为 …

H5获取微信openid封装方法

H5获取微信openid封装方法 目录1、前置配置条件2、封装并新建getOpenid.js文件2.1&#xff1a;处理code方法2.2&#xff1a;第一次获取到openid后&#xff0c;再次进入无需再次获取&#xff1b;2.3&#xff1a;页面调用方法 3、往期回顾总结&#xff1a; 目录 接到需求&#xf…

腾讯EdgeOne产品测评体验—Web安全的攻与防:云端防护一体化

目录 简介接入准备EdgeOne购买及接入服务器环境配置添加测试站点关闭防护 安全性能测试XSS攻击sql注入 站点加速测试代码测试通过在线工具对比测试Ping检测tcping网站测速 HTTPS证书 操作步骤优点 总结EdgeOne的优缺点 简介 EdgeOne&#xff0c;作为腾讯云推出的全新CDN解决方…

使用icpc tool进行滚榜操作

前言 参加ACM的同学都知道&#xff0c;比赛非常有趣的环节就是赛后的滚榜环节&#xff0c;所以为了一个比赛的完整性&#xff0c;自己办比赛时也想要加入滚榜的操作&#xff0c;经过一段时间的研究学习&#xff0c;已经可以将滚榜程序与domjudege程序成功完成融合&#xff0c;…

node.jd版本降级/升级

第一步.先清空本地安装的node.js版本 按健winR弹出窗口&#xff0c;键盘输入cmd,然后敲回车&#xff08;或者鼠标直接点击电脑桌面最左下角的win窗口图标弹出&#xff0c;输入cmd再点击回车键&#xff09; 进入命令控制行窗口&#xff0c;输入where node&#xff0c;查看本地…

CentOS7.9下载及安装教程

1. 下载CentOS7.9 CentOS用的最多的是7.6&#xff0c;7.9是7里面最新的&#xff0c;至于8以上的版本听说没有维护和更新了&#xff0c;这里以7.9为例。 下载&#xff1a;https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/ 2. 新建虚拟机 新建虚拟机–>典型(推荐…

【iOS开发】(一)2024 从一无所有开始,到ios开发(react Native)

​ 2024 从一无所有开始&#xff0c;到ios开发&#xff08;react Native&#xff09; 目录标题 1 工具简介2 基础环境搭建1 安装 brew2 安装 Node.js3 安装 Yarn4 安装 React Native 脚手架 3 ios环境搭建4创建并启动一个app 在这里插入图片描述 1 工具简介 Homebrew (brew)&a…

Window安装Redis

安装Redis-Service 下载并安装最新版Redis-windows &#xff1a; https://github.com/redis-windows/redis-windows 安装Redis-Manager Another Redis Desktop Manager 是一款优秀Redis桌面(GUI)管理客户端 参考链接 https://redis.io/

Python | Leetcode Python题解之第29题两数相除

题目&#xff1a; 题解&#xff1a; class Solution:def divide(self, dividend: int, divisor: int) -> int:INT_MIN, INT_MAX -2**31, 2**31 - 1# 考虑被除数为最小值的情况if dividend INT_MIN:if divisor 1:return INT_MINif divisor -1:return INT_MAX# 考虑除数为…

SAP SD学习笔记05 - SD中的一括处理(集中处理),出荷和请求的冻结(替代实现承认功能)

上一章讲了SD的重要概念&#xff0c;比如出荷Plant&#xff08;交货工厂&#xff09;&#xff0c;出荷Point&#xff08;装运点&#xff09;&#xff0c;输送计划&#xff0c;品目的可用性检查&#xff0c;一括纳入/分割纳入&#xff0c;仓库管理等。 SAP SD学习笔记04 - 出荷…