0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

OpenHarmony開發(fā)案例:【自定義通知】

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-04-15 15:58 ? 次閱讀

介紹

本示例使用[@ohos.notificationManager] 等接口,展示了如何初始化不同類型通知的通知內(nèi)容以及通知的發(fā)布、取消及桌面角標(biāo)的設(shè)置,通知類型包括基本類型、長文本類型、多行文本類型、圖片類型、帶按鈕的通知、點擊可跳轉(zhuǎn)到應(yīng)用的通知。

效果預(yù)覽:

image.png

使用說明

1.啟動應(yīng)用后,彈出是否允許發(fā)送通知的彈窗,點擊允許后開始操作;

2.點擊界面中對應(yīng)的按鈕發(fā)布不同類型的通知,下拉狀態(tài)欄,在通知欄可以看到發(fā)布的通知;

3.打開提示音和震動效果開關(guān)后,再點擊對應(yīng)按鈕發(fā)布不同類型的通知,在通知的同時會伴有提示音或震動效果;

4.點擊消息列表Tab頁,可以查看到剛才發(fā)送的消息,消息右邊會顯示數(shù)量,點擊相應(yīng)的消息可進(jìn)行消息讀取,取消相應(yīng)通知;

5.回到仿桌面,可以看到角標(biāo)數(shù)量,對應(yīng)消息數(shù)量(使用前需安裝并啟動[仿桌面應(yīng)用]);

6.點擊取消所有通知,可以取消本應(yīng)用發(fā)布的所有通知;

代碼解讀

鴻蒙開發(fā)文檔參考了:[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]

entry/src/main/ets/
|---Application
|---components
|   |---NotificationList.ets                 //通知列表控件
|   |---NotificationPublish.ets              //通知發(fā)送控件
|   |---TitleBar.ets                         //標(biāo)題控件
|---feature
|   |---NotificationOperations.ets           // 對外提供發(fā)布通知的接口
|---MainAbility
|---pages
|   |---Index.ets                            // 首頁
entry/src/ohosTest/ets/
|---test
|   |---Index.test.ets                       // 首頁的自動化測試    
notification/src/main/ets/
|---notification
|   |---NotificationContentUtil.ets          // 封裝各種通知的主體內(nèi)容
|   |---NotificationManagementUtil.ets       // 封裝消息列表,角標(biāo)設(shè)置的接口
|   |---NotificationRequestUtil.ets          // 接收通知的主體內(nèi)容,返回完整的通知
|   |---NotificationUtil.ets                 // 封裝允許發(fā)布通知、發(fā)布通知、關(guān)閉通知的接口
|   |---WantAgentUtil.ets                    // 封裝wantAgent
|---util                                     // 日志文件```

### 具體實現(xiàn)

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

* 允許發(fā)送通知、發(fā)送通知、取消通知的功能接口封裝在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();

* 允許發(fā)送通知:在進(jìn)入[Index.ets]前 通過notificationUtil.enableNotification()調(diào)用notification.requestEnableNotification()接口向用戶請求發(fā)送通知;
* 發(fā)送通知:通過publishNotification()封裝發(fā)布通知的接口;
* 取消通知:在[Index.ets]頁面中通過點擊事件調(diào)用cancelAllNotifications()取消所有的通知或者通過cancelNotificationById()取消指定id的通知;
* 獲取應(yīng)用所有消息通知、取消相關(guān)類型通知,角標(biāo)管理接口封裝在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']; // 多行文本通知的多行文本內(nèi)容

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;

// 在初始化函數(shù)初始化基本通知類型的參數(shù)

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

};

}

// 發(fā)布基本類型通知

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)}`);

}

}

// 發(fā)布長文本類型通知

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)}`);

}

}

// 發(fā)布多行文本類型通知

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)}`);

}

}

// 發(fā)布圖片類型通知

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)}`);

}

}

// 發(fā)布帶按鈕的通知

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)}`);

}

}

// 發(fā)布點擊跳轉(zhuǎn)到應(yīng)用的通知

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)}`);

}

}

}

* 獲取應(yīng)用所有消息通知:在constructor() 構(gòu)造函數(shù)中調(diào)用@ohos.notificationManager中的getActiveNotifications接口獲取所有通知及相應(yīng)類型通知數(shù)量,通過封裝getAllNotifications() 對外提供接口獲取當(dāng)前消息及消息數(shù)量。
* 取消相關(guān)類型通知:通過cancelNotificationType()封裝取消相關(guān)通知類型的接口;
* 角標(biāo)管理接口:通過setBadgeNumber()封裝設(shè)置應(yīng)用角標(biāo)數(shù)量的接口,通過getBadgeNumber()封裝獲取當(dāng)前應(yīng)用角標(biāo)數(shù)量的接口。
* 添加一條通知:通過addNotification()封裝接口添加一條通知到消息管理器,當(dāng)發(fā)送通知的時候進(jìn)行調(diào)用。
* NotificationOperations向外提供接口,在頁面中調(diào)用它們來實現(xiàn)功能,源碼參考:[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']; // 多行文本通知的多行文本內(nèi)容

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;

// 在初始化函數(shù)初始化基本通知類型的參數(shù)

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

};

}

// 發(fā)布基本類型通知

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)}`);

}

}

// 發(fā)布長文本類型通知

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)}`);

}

}

// 發(fā)布多行文本類型通知

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)}`);

}

}

// 發(fā)布圖片類型通知

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)}`);

}

}

// 發(fā)布帶按鈕的通知

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)}`);

}

}

// 發(fā)布點擊跳轉(zhuǎn)到應(yīng)用的通知

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)}`);

}

}

}

* 發(fā)布通知:在[Index.ets] 頁面中通過點擊事件調(diào)用NotificationOperations中封裝的對應(yīng)的方法,然后從NotificationContentUtil中獲取對應(yīng)的主體內(nèi)容content, 將content傳遞給NotificationRequestUtil得到完整的發(fā)布信息,最后調(diào)用NotificationUtil.publishNotification()發(fā)布內(nèi)容;
* 播放提示音、馬達(dá)震動的功能在NotificationUtil調(diào)用發(fā)布通知的接口處進(jìn)行判斷是否開啟,源碼參考:[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']; // 多行文本通知的多行文本內(nèi)容

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;

// 在初始化函數(shù)初始化基本通知類型的參數(shù)

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

};

}

// 發(fā)布基本類型通知

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)}`);

}

}

// 發(fā)布長文本類型通知

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)}`);

}

}

// 發(fā)布多行文本類型通知

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)}`);

}

}

// 發(fā)布圖片類型通知

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)}`);

}

}

// 發(fā)布帶按鈕的通知

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)}`);

}

}

// 發(fā)布點擊跳轉(zhuǎn)到應(yīng)用的通知

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)}`);

}

}

}

* 發(fā)布通知:在[Index.ets]通過publishNotification()封裝發(fā)布通知的接口的同時,根據(jù)NotificationUtil類中對應(yīng)變量的值判斷是否開啟了提示音或馬達(dá),若已開啟,則執(zhí)行對應(yīng)代碼段;
* 控制提示音或馬達(dá)的開關(guān):在[Index.ets]通過調(diào)用NotificationUtil類兩個方法對NotificationUtil類中對應(yīng)變量進(jìn)行更改,開啟為true,關(guān)閉為false;
* 自動化測試,對應(yīng)用接口或系統(tǒng)接口進(jìn)行單元測試,并且對基于UI操作進(jìn)行UI自動化測試
* 模擬點擊:在Index.test.ets的beforeAll中調(diào)用startAbility()拉起應(yīng)用并進(jìn)入首頁, 然后通過Driver的assertComponentExist、findComponent和findWindow等獲取到對應(yīng)組件的位置, 最后通過click()模擬出人工點擊對應(yīng)組件的效果;
* 模擬各種操作流程:在Index.test.ets 的每個it里面,按一定邏輯順序排好點擊組件的順序,從而模擬出人為操作的過程,最終,所有的it組成了整一個應(yīng)用的自動化測試。

審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 鴻蒙
    +關(guān)注

    關(guān)注

    56

    文章

    2267

    瀏覽量

    42486
  • OpenHarmony
    +關(guān)注

    關(guān)注

    25

    文章

    3548

    瀏覽量

    15737
收藏 人收藏

    評論

    相關(guān)推薦

    Android端自定義鈴聲 MobPush對安卓端自定義鈴聲的教程

    如何為APP推送設(shè)置獨(dú)特的通知鈴聲呢?本次帶來的是MobPush對安卓端自定義鈴聲的教程,快來看看吧~
    的頭像 發(fā)表于 10-21 15:34 ?1020次閱讀
    Android端<b class='flag-5'>自定義</b>鈴聲 MobPush對安卓端<b class='flag-5'>自定義</b>鈴聲的教程

    HarmonyOS開發(fā)實例:【自定義Emitter】

    使用[Emitter]實現(xiàn)事件的訂閱和發(fā)布,使用[自定義彈窗]設(shè)置廣告信息。
    的頭像 發(fā)表于 04-14 11:37 ?880次閱讀
    HarmonyOS<b class='flag-5'>開發(fā)</b>實例:【<b class='flag-5'>自定義</b>Emitter】

    HarmonyOS開發(fā)案例:【 自定義彈窗】

    基于ArkTS的聲明式開發(fā)范式實現(xiàn)了三種不同的彈窗,第一種直接使用公共組件,后兩種使用CustomDialogController實現(xiàn)自定義彈窗
    的頭像 發(fā)表于 05-16 18:18 ?1060次閱讀
    HarmonyOS<b class='flag-5'>開發(fā)案</b>例:【 <b class='flag-5'>自定義</b>彈窗】

    基于ArkTS語言的OpenHarmony APP應(yīng)用開發(fā)自定義通知

    () } } 4、項目編譯 4.1、打開項目 打開DevEco Studio,再打開自定義通知項目。 4.2、編譯程序 點擊菜單欄上的“Build” -> \"Rebuild
    發(fā)表于 09-14 15:12

    OpenHarmony應(yīng)用開發(fā)自定義彈窗

    本文轉(zhuǎn)載自《OpenHarmony應(yīng)用開發(fā)自定義彈窗》,作者:zhushangyuan_ ? 應(yīng)用場景 在應(yīng)用的使用和開發(fā)中,彈窗是一個很常見的場景,
    發(fā)表于 09-06 14:40

    1602自定義字符

    1602液晶能夠顯示自定義字符,能夠根據(jù)讀者的具體情況顯示自定義字符。
    發(fā)表于 01-20 15:43 ?1次下載

    怎么樣去開發(fā)自定義應(yīng)用程序?

    Atmel小貼士 如何開發(fā)自定義應(yīng)用程序
    的頭像 發(fā)表于 07-11 00:05 ?2279次閱讀

    OpenHarmony自定義組件:ClearableInput和Keyboard

    組件介紹: 本示例包含了兩個OpenHarmony自定義組件,一個是ClearableInput,另一個是Keyboard。 ClearableInput 定義了一個帶清空圖標(biāo)的文本輸入框
    發(fā)表于 03-18 15:21 ?1次下載
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定義</b>組件:ClearableInput和Keyboard

    OpenHarmony自定義組件FlowImageLayout

    組件介紹 本示例是OpenHarmony自定義組件FlowImageLayout。 用于將一個圖片列表以瀑布流的形式顯示出來。 調(diào)用方法
    發(fā)表于 03-21 10:17 ?3次下載
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定義</b>組件FlowImageLayout

    OpenHarmony自定義組件ProgressWithText

    組件介紹 本示例是OpenHarmony自定義組件ProgressWithText。 在原來進(jìn)度條的上方加了一個文本框,動態(tài)顯示當(dāng)前進(jìn)度并調(diào)整位置。 調(diào)用方法
    發(fā)表于 03-23 14:03 ?1次下載
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定義</b>組件ProgressWithText

    OpenHarmony自定義組件CircleProgress

    組件介紹 本示例是OpenHarmony自定義組件CircleProgress。 用于定義一個帶文字的圓形進(jìn)度條。 調(diào)用方法
    發(fā)表于 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.
    發(fā)表于 04-08 10:48 ?14次下載

    自定義算子開發(fā)

    一個完整的自定義算子應(yīng)用過程包括注冊算子、算子實現(xiàn)、含自定義算子模型轉(zhuǎn)換和運(yùn)行含自定義op模型四個階段。在大多數(shù)情況下,您的模型應(yīng)該可以通過使用hb_mapper工具完成轉(zhuǎn)換并順利部署到地平線芯片上……
    的頭像 發(fā)表于 04-07 16:11 ?2512次閱讀
    <b class='flag-5'>自定義</b>算子<b class='flag-5'>開發(fā)</b>

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

    labview超快自定義控件制作和普通自定義控件制作
    發(fā)表于 08-21 10:32 ?11次下載

    鴻蒙ArkUI實例:【自定義組件】

    組件是 OpenHarmony 頁面最小顯示單元,一個頁面可由多個組件組合而成,也可只由一個組件組合而成,這些組件可以是ArkUI開發(fā)框架自帶系統(tǒng)組件,比如?`Text`?、?`Button`?等,也可以是自定義組件,本節(jié)筆者簡
    的頭像 發(fā)表于 04-08 10:17 ?484次閱讀