精品国产人成在线_亚洲高清无码在线观看_国产在线视频国产永久2021_国产AV综合第一页一个的一区免费影院黑人_最近中文字幕MV高清在线视频

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

OpenHarmony開發案例:【自定義通知】

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

介紹

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

效果預覽:

image.png

使用說明

1.啟動應用后,彈出是否允許發送通知的彈窗,點擊允許后開始操作;

2.點擊界面中對應的按鈕發布不同類型的通知,下拉狀態欄,在通知欄可以看到發布的通知;

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

4.點擊消息列表Tab頁,可以查看到剛才發送的消息,消息右邊會顯示數量,點擊相應的消息可進行消息讀取,取消相應通知;

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

6.點擊取消所有通知,可以取消本應用發布的所有通知;

代碼解讀

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

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

### 具體實現

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

* 允許發送通知、發送通知、取消通知的功能接口封裝在NotificationUtil,源碼參考:[NotificationUtil.ets]

/*

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

*/

import notification from '@ohos.notificationManager'

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

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

const TAG: string = 'NotificationUtil'

class NotificationUtil {

private isPromptTone: boolean = false;

private isVibrationEffect: boolean = false;

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

this.isPromptTone = flag;

return this.isPromptTone;

}

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

this.isVibrationEffect = flag;

return this.isVibrationEffect;

}

/**

  • enable notification

*/

async enableNotification() {

try {

  await notification.requestEnableNotification();

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

} catch (err) {

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

}

}

/**

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

*/

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

if (id && id > 0) {

  notificationRequest.id = id;

}

try {

  let notificationSlot: notification.NotificationSlot = {

    type: notification.SlotType.CONTENT_INFORMATION,

    level: notification.SlotLevel.LEVEL_DEFAULT

  };

  if (this.isPromptTone) {

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

  }

  if (this.isVibrationEffect) {

    notificationSlot.vibrationEnabled = true;

    notificationSlot.vibrationValues = [200];

  }

  await notification.removeAllSlots();

  await notification.addSlot(notificationSlot.type);

  await notification.publish(notificationRequest);

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

  await notificationManagement.addNotification(notificationRequest);

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

} catch (err) {

  if (err) {

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

  }

}

}

/**

  • cancel notification by id

*/

async cancelNotificationById(id: number) {

try {

  await notification.cancel(id);

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

} catch (err) {

  if (err) {

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

  }

}

}

/**

  • cancel all notification

*/

async cancelAllNotifications() {

try {

  await notification.cancelAll();

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

} catch (err) {

  if (err) {

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

  }

}

}

}

export let notificationUtil = new NotificationUtil();

* 允許發送通知:在進入[Index.ets]前 通過notificationUtil.enableNotification()調用notification.requestEnableNotification()接口向用戶請求發送通知;
* 發送通知:通過publishNotification()封裝發布通知的接口;
* 取消通知:在[Index.ets]頁面中通過點擊事件調用cancelAllNotifications()取消所有的通知或者通過cancelNotificationById()取消指定id的通知;
* 獲取應用所有消息通知、取消相關類型通知,角標管理接口封裝在NotificationManagementUtil,源碼參考:[NotificationManagementUtil.ets]

/*

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

*/

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

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

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

const ABILITY_NAME: string = 'MainAbility';

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

const enum NOTIFICATION_ID { // 定義不同類型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函數初始化基本通知類型的參數

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

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

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

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 發布基本類型通知

publishBasicNotification = () = > {

try {

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

    logger.info(TAG, `publishBasicNotification`);

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

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

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

  }

} catch (error) {

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

}

}

// 發布長文本類型通知

publishLongTextNotification = () = > {

try {

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

    logger.info(TAG, `publishLongTextNotification`);

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

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布多行文本類型通知

publishMultiLineNotification = () = > {

try {

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

    logger.info(TAG, `publishMultiLineNotification`);

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布圖片類型通知

publishPictureNotification = async () = > {

try {

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

    logger.info(TAG, `publishPictureNotification`);

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

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

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

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

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

    let picture = await imageResource.createPixelMap();

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

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

  }

} catch (error) {

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

}

}

// 發布帶按鈕的通知

publishNotificationWithButtons = async () = > {

try {

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

    logger.info(TAG, `publishNotificationWithButtons`);

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

    let actionButtons: notification.NotificationActionButton[] = [

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

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

}

}

// 發布點擊跳轉到應用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

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

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

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

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

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

}

}

}

* 獲取應用所有消息通知:在constructor() 構造函數中調用@ohos.notificationManager中的getActiveNotifications接口獲取所有通知及相應類型通知數量,通過封裝getAllNotifications() 對外提供接口獲取當前消息及消息數量。
* 取消相關類型通知:通過cancelNotificationType()封裝取消相關通知類型的接口;
* 角標管理接口:通過setBadgeNumber()封裝設置應用角標數量的接口,通過getBadgeNumber()封裝獲取當前應用角標數量的接口。
* 添加一條通知:通過addNotification()封裝接口添加一條通知到消息管理器,當發送通知的時候進行調用。
* NotificationOperations向外提供接口,在頁面中調用它們來實現功能,源碼參考:[NotificationOperations.ets]

/*

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

*/

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

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

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

const ABILITY_NAME: string = 'MainAbility';

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

const enum NOTIFICATION_ID { // 定義不同類型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函數初始化基本通知類型的參數

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

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

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

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 發布基本類型通知

publishBasicNotification = () = > {

try {

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

    logger.info(TAG, `publishBasicNotification`);

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

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

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

  }

} catch (error) {

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

}

}

// 發布長文本類型通知

publishLongTextNotification = () = > {

try {

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

    logger.info(TAG, `publishLongTextNotification`);

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

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布多行文本類型通知

publishMultiLineNotification = () = > {

try {

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

    logger.info(TAG, `publishMultiLineNotification`);

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布圖片類型通知

publishPictureNotification = async () = > {

try {

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

    logger.info(TAG, `publishPictureNotification`);

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

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

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

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

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

    let picture = await imageResource.createPixelMap();

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

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

  }

} catch (error) {

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

}

}

// 發布帶按鈕的通知

publishNotificationWithButtons = async () = > {

try {

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

    logger.info(TAG, `publishNotificationWithButtons`);

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

    let actionButtons: notification.NotificationActionButton[] = [

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

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

}

}

// 發布點擊跳轉到應用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

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

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

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

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

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

}

}

}

* 發布通知:在[Index.ets] 頁面中通過點擊事件調用NotificationOperations中封裝的對應的方法,然后從NotificationContentUtil中獲取對應的主體內容content, 將content傳遞給NotificationRequestUtil得到完整的發布信息,最后調用NotificationUtil.publishNotification()發布內容;
* 播放提示音、馬達震動的功能在NotificationUtil調用發布通知的接口處進行判斷是否開啟,源碼參考:[NotificationOperations.ets]

/*

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

*/

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

import {

logger,

notificationUtil,

notificationContentUtil,

notificationRequestUtil,

wantAgentUtil

} from '@ohos/notification';

import notification from '@ohos.notificationManager';

interface notificationIdType {

BASIC: number,

LONG_TEXT: number,

MULTI_LINE: number,

PICTURE: number,

BUTTON: number,

WANTAGENT: number

};

const TAG: string = 'NotificationOperations';

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

const ABILITY_NAME: string = 'MainAbility';

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

const enum NOTIFICATION_ID { // 定義不同類型通知的通知id

BASIC = 1,

LONG_TEXT = 2,

MULTI_LINE = 3,

PICTURE = 4,

BUTTON = 5,

WANTAGENT = 6

};

export default class NotificationOperations {

private context: Context | undefined = undefined;

private basicContent: notification.NotificationBasicContent | undefined = undefined;

// 在初始化函數初始化基本通知類型的參數

constructor(context: Context) {

this.context = context;

let notificationTitle = '';

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

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

this.basicContent = {

  title: notificationTitle,

  text: notificationText,

  additionalText: notificationAdditional

};

}

// 發布基本類型通知

publishBasicNotification = () = > {

try {

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

    logger.info(TAG, `publishBasicNotification`);

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

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

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

  }

} catch (error) {

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

}

}

// 發布長文本類型通知

publishLongTextNotification = () = > {

try {

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

    logger.info(TAG, `publishLongTextNotification`);

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

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布多行文本類型通知

publishMultiLineNotification = () = > {

try {

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

    logger.info(TAG, `publishMultiLineNotification`);

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

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

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

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

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

  }

} catch (error) {

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

}

}

// 發布圖片類型通知

publishPictureNotification = async () = > {

try {

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

    logger.info(TAG, `publishPictureNotification`);

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

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

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

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

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

    let picture = await imageResource.createPixelMap();

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

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

  }

} catch (error) {

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

}

}

// 發布帶按鈕的通知

publishNotificationWithButtons = async () = > {

try {

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

    logger.info(TAG, `publishNotificationWithButtons`);

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

    let actionButtons: notification.NotificationActionButton[] = [

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')

      },

      {

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

        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)

      }

    ]

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.BUTTON);

  }

} catch (error) {

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

}

}

// 發布點擊跳轉到應用的通知

publishNotificationWithWantAgent = async () = > {

try {

  logger.info(TAG, `publishNotificationWithWantAgent`);

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

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

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

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

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

    notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID.WANTAGENT);

  }

} catch (error) {

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

}

}

}

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

審核編輯 黃宇

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 鴻蒙
    +關注

    關注

    57

    文章

    2310

    瀏覽量

    42743
  • OpenHarmony
    +關注

    關注

    25

    文章

    3660

    瀏覽量

    16156
收藏 人收藏

    評論

    相關推薦

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

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

    HarmonyOS開發實例:【自定義Emitter】

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

    HarmonyOS開發案例:【 自定義彈窗】

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

    基于ArkTS語言的OpenHarmony APP應用開發自定義通知

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

    OpenHarmony應用開發自定義彈窗

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

    1602自定義字符

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

    怎么樣去開發自定義應用程序?

    Atmel小貼士 如何開發自定義應用程序
    的頭像 發表于 07-11 00:05 ?2344次閱讀

    OpenHarmony自定義組件:ClearableInput和Keyboard

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

    OpenHarmony自定義組件FlowImageLayout

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

    OpenHarmony自定義組件ProgressWithText

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

    OpenHarmony自定義組件CircleProgress

    組件介紹 本示例是OpenHarmony自定義組件CircleProgress。 用于定義一個帶文字的圓形進度條。 調用方法
    發表于 03-23 14:06 ?4次下載
    <b class='flag-5'>OpenHarmony</b><b class='flag-5'>自定義</b>組件CircleProgress

    自定義視圖組件教程案例

    自定義組件 1.自定義組件-particles(粒子效果) 2.自定義組件- pulse(脈沖button效果) 3.自定義組件-progress(progress效果) 4.
    發表于 04-08 10:48 ?14次下載

    自定義算子開發

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

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

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

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

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