介紹
本示例使用[@ohos.notificationManager] 等接口,展示了如何初始化不同類型通知的通知內容以及通知的發布、取消及桌面角標的設置,通知類型包括基本類型、長文本類型、多行文本類型、圖片類型、帶按鈕的通知、點擊可跳轉到應用的通知。
效果預覽:
使用說明
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
發布評論請先 登錄
相關推薦
評論