鴻蒙HarmonyOS實戰(zhàn)-ArkTS語言基礎類庫(通知)
??前言
移動應用中的通知是指應用程序發(fā)送給用戶的一種提示或提醒消息。這些通知可以在用戶設備的通知中心或狀態(tài)欄中顯示,以提醒用戶有關應用程序的活動、事件或重要信息。
移動應用中的通知可以分為兩種類型:本地通知和遠程通知。
本地通知是由應用程序自身發(fā)起的通知,不需要連接到遠程服務器。應用程序可以根據(jù)特定條件或事件觸發(fā)本地通知,例如定時提醒、任務完成等。本地通知可以直接在設備上顯示,即使應用程序未運行,用戶也能收到通知。
遠程通知是由遠程服務器發(fā)送給應用程序的通知。應用程序需要與遠程服務器建立連接,以接收和處理遠程通知。遠程通知可以用于各種目的,如推送新聞、推廣促銷活動、提醒用戶更新等。
無論是本地通知還是遠程通知,移動應用中的通知通常都具有以下特點:
-
可定制性:應用程序可以自定義通知的內(nèi)容、標題、圖標等,以便向用戶提供個性化的體驗。
-
交互性:通知可以包含操作按鈕或鏈接,用戶可以通過點擊通知來執(zhí)行特定的操作,如打開應用、查看詳情等。
-
靜默通知:某些通知可以以靜默模式發(fā)送,即用戶不會收到任何視覺或聲音提示,但應用程序仍可以在后臺處理通知。
-
優(yōu)先級控制:應用程序可以為通知設置優(yōu)先級,以便在設備上顯示不同的通知樣式或觸發(fā)不同的提示音。
??一、通知
??1.通知概述
??1.1 通知簡介
HarmonyOS應用可以通過通知接口發(fā)送通知消息。開發(fā)者可以使用該接口發(fā)送各種類型的通知,包括普通通知、長文字通知、大圖通知等。終端用戶可以通過通知欄查看通知內(nèi)容,并進行相應操作,比如點擊通知來打開應用。
通過通知接口,開發(fā)者可以設置通知的標題、內(nèi)容、圖標、優(yōu)先級等屬性。可以通過設置點擊通知后的跳轉(zhuǎn)動作,實現(xiàn)點擊通知打開應用的功能。此外,開發(fā)者還可以通過設置通知的聲音、震動等效果,提升用戶體驗。
通知常見的使用場景:
-
提醒用戶有待辦事項,如鬧鐘、日歷事件等。
-
通知用戶設備的狀態(tài),如電量低、網(wǎng)絡連接狀態(tài)等。
-
提醒用戶有新的郵件、社交媒體消息等。
-
顯示其他應用的提醒、通知,如電話、音樂播放器、定時器等。
-
顯示系統(tǒng)級別的通知,如系統(tǒng)更新、權限請求等。
-
提醒用戶有新的軟件更新、安全補丁等。
-
通知用戶有新的活動、促銷等。
-
提醒用戶有新的天氣預報、股票行情等。
-
顯示其他應用的報警、警報等緊急通知。
HarmonyOS通過Advanced Notification Service(ANS)為應用程序提供通知管理服務。ANS支持多種通知類型,包括基礎類型通知和進度條類型通知。
基礎類型通知是一種簡單的通知樣式,用于顯示重要的文本信息或簡短的通知內(nèi)容。它可以包含標題、內(nèi)容和圖標,用戶可以通過點擊通知來執(zhí)行相關操作。
進度條類型通知用于顯示任務進度或下載進度等信息。它除了包含基礎類型通知的內(nèi)容外,還可以添加一個進度條,以便用戶了解任務的進度情況。
??1.2 通知業(yè)務流程
通知子系統(tǒng)是一個中間件,負責接收來自通知發(fā)送端的通知消息,并將這些消息分發(fā)給訂閱端。它起到了消息調(diào)度和分發(fā)的作用,實現(xiàn)了發(fā)布-訂閱模式。
通知發(fā)送端是產(chǎn)生通知消息的組件,可以是應用程序、系統(tǒng)模塊等。它負責生成通知消息,并通過IPC通信機制將消息發(fā)送到通知子系統(tǒng)。
通知訂閱端是接收通知消息的組件,可以是應用程序、監(jiān)控工具等。它通過訂閱通知子系統(tǒng),接收特定類型的通知消息。
整個通知業(yè)務流程如下:
- 通知發(fā)送端生成一條通知消息,包括通知的類型、內(nèi)容等。
- 通知發(fā)送端通過IPC通信機制將通知消息發(fā)送到通知子系統(tǒng)。
- 通知子系統(tǒng)接收到通知消息后,根據(jù)消息的類型和訂閱端的訂閱情況,將消息分發(fā)給相應的訂閱端。
- 訂閱端接收到通知消息后,進行相應的處理,比如展示通知內(nèi)容、觸發(fā)某些操作等。
通過通知子系統(tǒng)的中間件架構(gòu),可以實現(xiàn)高效的通知消息分發(fā)。通知發(fā)送端和訂閱端之間解耦,可以獨立開發(fā)和部署,提高了系統(tǒng)的可擴展性和可維護性。同時,通過訂閱機制,訂閱端可以選擇性地接收感興趣的通知消息,提高了系統(tǒng)的靈活性。

??2.發(fā)布通知
??2.1 發(fā)布基礎類型通知
基礎類型通知可以用來發(fā)送各種類型的通知,包括短信息、提示信息和廣告推送等。它們可以包含普通文本、長文本、多行文本和圖片等。

例如,你可以發(fā)送一條包含簡短文字的通知來提醒用戶某個事件即將發(fā)生,或者發(fā)送一條包含長文本的通知來提供詳細的信息。此外,你還可以發(fā)送一條包含多行文本的通知,每行顯示一條信息。如果需要顯示圖片,你可以發(fā)送一條包含圖片的通知。基礎類型通知非常靈活,可以根據(jù)具體需求來進行設置。
??2.1.1 接口說明

??2.1.2 開發(fā)步驟
在HarmonyOS中,NotificationRequest類是用于創(chuàng)建通知的一個重要類。通過NotificationRequest類,可以設置通知的各種屬性,如標題、內(nèi)容、圖標、聲音、震動等。
??2.1.2.1 普通文本類型
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本類型通知
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
}
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
})
}
.width('100%')
}
.height('100%')
}
}

??2.1.2.2 長文本類型通知
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 長文本類型通知
longText: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
longText: 'test_longText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
}
}
}
// 發(fā)布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

??2.1.2.3 多行文本類型通知
import NotificationManager from '@ohos.notificationManager';
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本類型通知
multiLine: {
title: 'test_title',
text: 'test_text',
briefText: 'test_briefText',
longTitle: 'test_longTitle',
lines: ['line_01', 'line_02', 'line_03', 'line_04'],
}
}
}
// 發(fā)布通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

??2.1.2.4 圖片類型通知
import NotificationManager from '@ohos.notificationManager';
import image from '@ohos.multimedia.image';
// 圖片構(gòu)造
const color = new ArrayBuffer(60000);
let bufferArr = new Uint8Array(color);
for (var i = 0; i<bufferArr.byteLength;i++) {
bufferArr[i++] = 60;
bufferArr[i++] = 20;
bufferArr[i++] = 220;
bufferArr[i] = 100;
}
let opts = { editable:true, pixelFormat:"ARGB_8888", size: {height:100, width : 150}};
image
// @ts-ignore
.createPixelMap(color, opts)
.then(async (pixelmap) => {
await pixelmap.getImageInfo().then(imageInfo => {
console.log("=====size: ====" + JSON.stringify(imageInfo.size));
}).catch(err => {
console.error("Failed to obtain the image pixel map information." + JSON.stringify(err));
return;
})
let notificationRequest = {
id: 1,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
picture: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
picture: pixelmap,
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
}
},
}
// 發(fā)送通知
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
}).catch(err=>{
console.error('create pixelmap failed =========='+ JSON.stringify(err));
return;
})
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

??2.2 發(fā)布進度條類型通知
??2.2.1 接口說明

??2.2.2 開發(fā)步驟
import NotificationManager from '@ohos.notificationManager';
NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`);
let isSupportTpl: boolean = data; // isSupportTpl的值為true表示支持支持downloadTemplate模板類通知,false表示不支持
// ...
}).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});
let template = {
name:'downloadTemplate',
data: {
title: '標題:',
fileName: 'music.mp4',
progressValue: 30,
progressMaxValue:100,
}
}
//構(gòu)造NotificationRequest對象
let notificationRquest = {
id: 1,
slotType: NotificationManager.SlotType.OTHER_TYPES,
template: template,
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: template.data.title + template.data.fileName,
text: "sendTemplate",
additionalText: "30%"
}
},
deliveryTime: new Date().getTime(),
showDeliveryTime: true
}
NotificationManager.publish(notificationRquest).then(() => {
console.info(`[ANS] publish success `);
}).catch((err) => {
console.error(`[ANS] failed to publish, error[${err}]`);
});
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

??2.3 為通知添加行為意圖
WantAgent是HarmonyOS提供的一種功能,它允許開發(fā)者封裝行為意圖。行為意圖主要用于拉起指定的應用組件或發(fā)布公共事件等。在HarmonyOS中,我們可以通過通知的方式將WantAgent從發(fā)布方傳遞給接收方,從而在接收方觸發(fā)WantAgent中指定的意圖。
舉個例子,假設有一個應用發(fā)布一個通知消息,通常希望用戶能夠通過點擊通知欄來打開目標應用組件。為了實現(xiàn)這個目標,開發(fā)者可以將WantAgent封裝到通知消息中。當系統(tǒng)接收到帶有WantAgent的通知消息時,用戶點擊通知欄時會觸發(fā)WantAgent中指定的意圖,從而打開目標應用組件。
為了實現(xiàn)通知中的行為意圖,應用需要向應用組件管理服務(AMS)申請WantAgent,并將其與其他通知信息一起發(fā)送給桌面。當用戶在桌面通知欄上點擊通知時,系統(tǒng)會觸發(fā)WantAgent的動作,從而實現(xiàn)目標應用組件的打開。

??2.3.1 接口說明

??2.3.2 開發(fā)步驟
import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentObj = null; // 用于保存創(chuàng)建成功的wantAgent對象,后續(xù)使用其完成觸發(fā)的動作。
// 通過WantAgentInfo的operationType設置動作類型。
let wantAgentInfo = {
wants: [
{
deviceId: '',
bundleName: 'com.example.test',
abilityName: 'com.example.test.MainAbility',
action: '',
entities: [],
uri: '',
parameters: {}
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
// // wantAgentInfo
// let wantAgentInfo = {
// wants: [
// {
// action: 'event_name', // 設置事件名。
// parameters: {},
// }
// ],
// operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
// requestCode: 0,
// wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
// }
// 創(chuàng)建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
if (err) {
console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
} else {
console.info('[WantAgent]getWantAgent success');
wantAgentObj = data;
}
});
// 構(gòu)造NotificationRequest對象
let notificationRequest = {
content: {
contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'Test_Title',
text: 'Test_Text',
additionalText: 'Test_AdditionalText',
},
},
id: 1,
label: 'TEST',
//wantAgent: wantAgentObj,//好像報錯
}
// 通知發(fā)送
NotificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

??寫在最后
- 如果你覺得這篇內(nèi)容對你還蠻有幫助,我想邀請你幫我三個小忙:
- 點贊,轉(zhuǎn)發(fā),有你們的 『點贊和評論』,才是我創(chuàng)造的動力。
- 關注小編,同時可以期待后續(xù)文章ing??,不定期分享原創(chuàng)知識。
- 更多鴻蒙最新技術知識點,請關注作者博客:https://t.doruo.cn/14DjR1rEY


浙公網(wǎng)安備 33010602011771號