메시지 알림을 클릭하면 애플리케이션 페이지로 이동합니다
Source: Dev.to
Problem description
Notification Kit을 사용하여 메시지를 보낼 때 알림에 행동 의도를 추가하고 애플리케이션의 지정된 페이지로 리디렉션하는 방법은?
Background knowledge
알림을 발행할 때 사용자가 알림 바를 클릭하여 대상 애플리케이션 컴포넌트를 띄우거나 공개 이벤트를 발생시키길 기대한다면, Ability Kit을 통해 WantAgent를 신청하여 알림 메시지에 캡슐화할 수 있습니다.
문서는 다음을 참고하세요:
Solution
-
Apply for notification permission in the code
enableNotifications() { const requestEnableNotificationCallback = (err: BusinessError): void => { if (err) { hilog.error(0x0000, 'testTag', `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); } else { hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`); } }; notificationManager.requestEnableNotification(this.context, requestEnableNotificationCallback); } -
Create
WantAgentInfoand publish a notificationButton('click').onClick(() => { let wantAgentObj: WantAgent; const wantAgentInfo: wantAgent.WantAgentInfo = { wants: [ { deviceId: '', bundleName: 'com.example.ir_wantagent', abilityName: 'EntryAbility', action: '', entities: [], uri: '', parameters: { targetPage: 'Index2' // Add target page parameters } } ], actionType: wantAgent.OperationType.START_ABILITY, requestCode: 0, wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG] }; wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to get want agent. Code is ${err.code}, message is ${err.message}`); return; } hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in getting want agent.'); wantAgentObj = data; const notificationRequest: notificationManager.NotificationRequest = { content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: 'Test_Title', text: 'Test_Text', additionalText: 'Test_AdditionalText', }, }, id: 6, label: 'TEST', wantAgent: wantAgentObj, }; notificationManager.publish(notificationRequest, (err: BusinessError) => { if (err) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`); return; } hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.'); }); }); }); -
Handle the intent in
EntryAbility.etsHot start – when the application is already running:
// Hot start onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { const targetPage = want.parameters?.targetPage; console.info(`onNewWant Received parameter: ${targetPage}`); if (targetPage === 'Index2') { router.pushUrl({ url: 'pages/Index2' }); } }Cold start – when the application is not running:
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); this.funcAbilityWant = want; } onWindowStageCreate(windowStage: window.WindowStage): void { let url = 'pages/Index'; if (this.funcAbilityWant?.parameters?.targetPage === 'Index2') { url = 'pages/Index2'; // New page to navigate to } console.info(`url:${url}`); windowStage.loadContent(url, (err) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); }); } -
Add a new
Index2pagePages 폴더를 오른쪽 클릭 → New → Page → New Page를 선택하고 이름을
Index2로 지정하면Index2.ets가 생성됩니다. -
Simulate clicking a message to jump to the page
Cold start: 알림을 보낸 뒤 멀티태스킹 화면에서 앱을 종료하고 알림을 클릭하면 앱이 바로
Index2로 실행됩니다.Hot start: 알림을 보낸 뒤 앱을 백그라운드로 보낸 다음 알림을 클릭하면 실행 중인 앱이
Index2로 이동합니다.
Complete example – Index.ets
import { common, wantAgent, WantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { notificationManager } from '@kit.NotificationKit';
const TAG = '[PublishOperation]';
const DOMAIN_NUMBER = 0xFF00;
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
private context = getContext(this) as common.UIAbilityContext;
enableNotifications() {
const requestEnableNotificationCallback = (err: BusinessError): void => {
if (err) {
hilog.error(0x0000, 'testTag',
`[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
} else {
hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
}
};
notificationManager.requestEnableNotification(this.context, requestEnableNotificationCallback);
}
// ... (rest of the component logic, including the button click shown in step 2)
}
전체 원본 토론은 아래를 참고하세요: