1. 기초 알림 구현
HarmonyOS 앱에서 사용자의 주의를 끌거나 시스템의 변화를 알리기 위해 알림(Notification) 기능을 활용합니다. 사용자는 알림 센터를 통해 전달된 메시지를 확인하고 앱과 상호작용할 수 있습니다.
알림 기능을 구현하기 위해 먼저 notificationManager 모듈을 가져와야 합니다.
import notificationManager from '@ohos.notificationManager';
알림을 게시할 때는 알림의 식별자(ID)와 내용이 포함된 NotificationRequest 객체를 생성합니다. publish 메서드는 Promise를 반환하므로 비동기 처리가 가능합니다.
// 알림 요청 구성
const alertId = 1001;
let simpleRequest = {
id: alertId,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: '시스템 업데이트',
text: '새로운 소프트웨어 버전이 준비되었습니다.',
additionalText: '지금 바로 확인해보세요'
}
}
};
// 알림 게시 실행
notificationManager.publish(simpleRequest)
.then(() => {
console.info('Notification sent successfully.');
})
.catch((err) => {
console.error(`Notification failed: ${err.code}, ${err.message}`);
});
더 이상 필요하지 않은 알림은 특정 ID를 지정하여 제거하거나, 현재 앱에서 발행한 모든 알림을 한꺼번에 취소할 수 있습니다.
// 특정 ID의 알림만 삭제
notificationManager.cancel(alertId);
// 모든 활성 알림 일괄 삭제
notificationManager.cancelAll();
2. 진행 상태를 표시하는 프로그레스 바 알림
파일 다운로드나 백그라운드 작업과 같이 시간이 소요되는 태스크의 경우, 사용자에게 현재 진행률을 시각적으로 보여주는 것이 좋습니다. HarmonyOS는 이를 위해 진행 상태 템플릿을 제공합니다.
템플릿을 사용하기 전, 현재 기기에서 해당 템플릿(downloadTemplate)을 지원하는지 확인하는 과정이 필요합니다.
async function checkAndSendProgress() {
const TEMPLATE_NAME = 'downloadTemplate';
let isAvailable = await notificationManager.isSupportTemplate(TEMPLATE_NAME);
if (!isAvailable) {
console.warn('Progress template is not supported on this device.');
return;
}
let currentVal = 65; // 현재 진행도
let maxVal = 100; // 전체 작업량
let progressRequest = {
id: 2001,
template: {
name: TEMPLATE_NAME,
data: {
progressValue: currentVal,
progressMaxValue: maxVal
}
},
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: '리소스 다운로드 중...',
text: '필요한 파일을 서버에서 가져오고 있습니다.',
additionalText: `${currentVal}%`
}
}
};
await notificationManager.publish(progressRequest);
}
3. WantAgent를 이용한 사용자 상호작용 제어
알림을 단순히 보여주는 것에 그치지 않고, 사용자가 알림을 클릭했을 때 특정 Ability를 실행하거나 이벤트를 발생시키기 위해 WantAgent를 설정합니다.
import wantAgent from '@ohos.app.ability.wantAgent';
async function createInteractionNotification() {
// 1. 동작 정의 (WantAgentInfo)
let agentParams = {
wants: [
{
bundleName: 'com.example.tech.app',
abilityName: 'MainAbility',
action: 'action.view.details',
entities: []
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
};
// 2. WantAgent 인스턴스 생성
let agentInstance = await wantAgent.getWantAgent(agentParams);
// 3. 알림 요청에 상호작용 의도 결합
let interactiveRequest = {
id: 3001,
wantAgent: agentInstance, // 클릭 시 실행될 의도 설정
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: '메시지 도착',
text: '새로운 메시지가 확인되었습니다. 클릭하여 답장하세요.'
}
}
};
notificationManager.publish(interactiveRequest);
}