介紹
本示例使用[@ohos.notificationManager] 等接口,展示了如何初始化不同類型通知的通知內(nèi)容以及通知的發(fā)布、取消及桌面角標(biāo)的設(shè)置,通知類型包括基本類型、長(zhǎng)文本類型、多行文本類型、圖片類型、帶按鈕的通知、點(diǎn)擊可跳轉(zhuǎn)到應(yīng)用的通知。
效果預(yù)覽:
使用說明
1.啟動(dòng)應(yīng)用后,彈出是否允許發(fā)送通知的彈窗,點(diǎn)擊允許后開始操作;
2.點(diǎn)擊界面中對(duì)應(yīng)的按鈕發(fā)布不同類型的通知,下拉狀態(tài)欄,在通知欄可以看到發(fā)布的通知;
3.打開提示音和震動(dòng)效果開關(guān)后,再點(diǎn)擊對(duì)應(yīng)按鈕發(fā)布不同類型的通知,在通知的同時(shí)會(huì)伴有提示音或震動(dòng)效果;
4.點(diǎn)擊消息列表Tab頁,可以查看到剛才發(fā)送的消息,消息右邊會(huì)顯示數(shù)量,點(diǎn)擊相應(yīng)的消息可進(jìn)行消息讀取,取消相應(yīng)通知;
5.回到仿桌面,可以看到角標(biāo)數(shù)量,對(duì)應(yīng)消息數(shù)量(使用前需安裝并啟動(dòng)[仿桌面應(yīng)用]);
6.點(diǎn)擊取消所有通知,可以取消本應(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 // 對(duì)外提供發(fā)布通知的接口
|---MainAbility
|---pages
| |---Index.ets // 首頁
entry/src/ohosTest/ets/
|---test
| |---Index.test.ets // 首頁的自動(dòng)化測(cè)試
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 // 日志文件```
### 具體實(shí)現(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()接口向用戶請(qǐng)求發(fā)送通知;
* 發(fā)送通知:通過publishNotification()封裝發(fā)布通知的接口;
* 取消通知:在[Index.ets]頁面中通過點(diǎn)擊事件調(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ā)布長(zhǎng)文本類型通知
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ā)布點(diǎn)擊跳轉(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() 對(duì)外提供接口獲取當(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ā)送通知的時(shí)候進(jìn)行調(diào)用。
* NotificationOperations向外提供接口,在頁面中調(diào)用它們來實(shí)現(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ā)布長(zhǎng)文本類型通知
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ā)布點(diǎn)擊跳轉(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ǎn)擊事件調(diào)用NotificationOperations中封裝的對(duì)應(yīng)的方法,然后從NotificationContentUtil中獲取對(duì)應(yīng)的主體內(nèi)容content, 將content傳遞給NotificationRequestUtil得到完整的發(fā)布信息,最后調(diào)用NotificationUtil.publishNotification()發(fā)布內(nèi)容;
* 播放提示音、馬達(dá)震動(dòng)的功能在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ā)布長(zhǎng)文本類型通知
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ā)布點(diǎn)擊跳轉(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ā)布通知的接口的同時(shí),根據(jù)NotificationUtil類中對(duì)應(yīng)變量的值判斷是否開啟了提示音或馬達(dá),若已開啟,則執(zhí)行對(duì)應(yīng)代碼段;
* 控制提示音或馬達(dá)的開關(guān):在[Index.ets]通過調(diào)用NotificationUtil類兩個(gè)方法對(duì)NotificationUtil類中對(duì)應(yīng)變量進(jìn)行更改,開啟為true,關(guān)閉為false;
* 自動(dòng)化測(cè)試,對(duì)應(yīng)用接口或系統(tǒng)接口進(jìn)行單元測(cè)試,并且對(duì)基于UI操作進(jìn)行UI自動(dòng)化測(cè)試
* 模擬點(diǎn)擊:在Index.test.ets的beforeAll中調(diào)用startAbility()拉起應(yīng)用并進(jìn)入首頁, 然后通過Driver的assertComponentExist、findComponent和findWindow等獲取到對(duì)應(yīng)組件的位置, 最后通過click()模擬出人工點(diǎn)擊對(duì)應(yīng)組件的效果;
* 模擬各種操作流程:在Index.test.ets 的每個(gè)it里面,按一定邏輯順序排好點(diǎn)擊組件的順序,從而模擬出人為操作的過程,最終,所有的it組成了整一個(gè)應(yīng)用的自動(dòng)化測(cè)試。
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
57文章
2392瀏覽量
43048 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3744瀏覽量
16573
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論