点击消息通知跳转到应用页面

发布: (2025年12月5日 GMT+8 17:46)
4 min read
原文: Dev.to

Source: Dev.to

问题描述

在使用 Notification Kit 发送消息时,如何为通知添加行为意图,并在点击通知后跳转到应用的指定页面?

背景知识

发布通知时,如果希望用户点击通知栏后拉起目标应用组件或发布公共事件,可以通过 Ability Kit 申请 WantAgent 并将其封装到通知消息中。
参考文档:

解决方案

  1. 在代码中申请通知权限

    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);
    }
  2. 创建 WantAgentInfo 并发布通知

    Button('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.');
        });
      });
    });
  3. EntryAbility.ets 中处理意图

    热启动 – 应用已经在运行时:

    // 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' });
      }
    }

    冷启动 – 应用未运行时:

    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.');
      });
    }
  4. 新增 Index2 页面

    Pages 文件夹上右键 → NewPageNew Page,命名为 Index2,系统会生成 Index2.ets

  5. 模拟点击消息跳转页面

    冷启动:发送通知后,在多任务视图中强制结束应用,然后点击通知——应用直接启动到 Index2 页面。

    热启动:发送通知后,将应用切入后台,然后点击通知——正在运行的应用会跳转到 Index2 页面。

完整示例 – 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)
}

完整的原始讨论请参见:

Back to Blog

相关文章

阅读更多 »