HarmonyOS 鸿蒙Next中通知消息点击跳转

HarmonyOS 鸿蒙Next中通知消息点击跳转 通知消息怎么点击跳转到app呢?

5 回复

背景知识:

  • requestEnableNotification():为确保应用可正常收到消息,应用发送通知前调用该方法弹出提醒,告知用户需要允许接收通知消息。详情请参见Notification Kit-请求通知授权
  • 信息传递载体WantWant是一种对象,用于在应用组件之间传递信息。
  • Notification Kit(用户通知服务):提供本地通知发布通道,开发者可借助Notification Kit将应用产生的通知直接在客户端本地推送给用户(相关API参考)。
  • 为通知添加行为意图
  • 当发布通知时,如果期望用户可以通过点击通知栏拉起目标应用组件或发布公共事件,可以通过Ability Kit(程序框架服务)申请WantAgent封装至通知消息中。
  • Push Kit(推送服务):华为提供的消息推送平台,建立了从云端到终端的消息推送通道。您通过集成推送服务,可以向客户端应用实时推送消息(HarmonyOS应用推送服务开发)。
  • 点击消息动作:云侧发送消息时clickAction中携带data字段并设置actionType字段。actionType:点击消息动作,0表示点击消息后进入首页,1表示点击消息后进入应用内页。当本字段设置为1时,uri和action至少填写一个,若都填写优先寻找与action匹配的应用页面。action:表示能够接收Want的action值的集合,取值可以自定义。uri:表示与Want中uris相匹配的集合,uris规则请参见skills标签data:点击消息时携带的JSON格式的数据。
  • 点击消息进入应用首页:项目模块级别下的src/main/module.json5中的skills标签配置,其中用于标识应用首页的skill(即配置了"entity.system.home"和"action.system.home"的skill)中不配置uris。
  • 点击消息进入应用内页:项目模块级别下的src/main/module.json5中设置目标Ability中skills标签的actions或uris值,两种方式如下:方式一:在skills标签中新增一个独立的skill对象,配置actions参数用于点击消息进入应用内页。方式二:在skills标签中新增一个独立的skill对象,配置uris参数用于点击消息进入应用内页(必须同时配置actions参数和uris参数,actions参数为空)。
  • request.agent.create:使用其创建要上传或下载的任务,在config中配置gauge(后台任务的过程进度通知策略)也能实现相应通知。

实现方法:

1.创建WantAgentInfo信息,创建拉起UIAbility的WantAgent的WantAgentInfo信息。

let wantAgentObj:WantAgent; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。

// 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo:wantAgent.WantAgentInfo = {
  wants: [
    {
      deviceId: '',
      bundleName: 'com.samples.notification',
      abilityName: 'SecondAbility',
      action: '',
      entities: [],
      uri: '',
      parameters: {}
    }
  ],
  actionType: wantAgent.OperationType.START_ABILITY,
  requestCode: 0,
  wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
};

创建发布公共事件的WantAgent的WantAgentInfo信息。

let wantAgentObj:WantAgent; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。

// 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo:wantAgent.WantAgentInfo = {
  wants: [
    {
      action: 'event_name', // 设置事件名
      parameters: {},
    }
  ],
  actionType: wantAgent.OperationType.SEND_COMMON_EVENT,
  requestCode: 0,
  wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
};

2.调用getWantAgent()方法进行创建WantAgent。

// 创建WantAgent
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;
});

3.构造NotificationRequest对象,并发布WantAgent通知。用户通过点击通知栏上的通知,系统会自动触发WantAgent的动作

// 构造NotificationRequest对象
let 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',
  // wantAgentObj使用前需要保证已被赋值(即步骤3执行完成)
  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.');
});

参考文档:点击应用推送的通知无法跳转-行业常见问题-新闻阅读类行业实践-行业实践 - 华为HarmonyOS开发者

更多关于HarmonyOS 鸿蒙Next中通知消息点击跳转的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


当发布通知时,如果期望用户可以通过点击通知栏拉起目标应用组件或发布公共事件,可以通过Ability Kit申请WantAgent封装至通知消息中。

  1. 代码中申请通知权限:
enableNotifications() {
  let 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);
}
  1. 创建WantAgentInfo信息并填写需要拉起的应用bundleName和abilityName(应用只能设置自己应用的bundleName和abilityName),然后构造NotificationRequest对象并发布通知:
Button('点击发送通知消息').onClick(() => {
  let wantAgentObj: WantAgent;
  let wantAgentInfo: wantAgent.WantAgentInfo = {
    wants: [
      {
        deviceId: '',
        bundleName: 'com.example.ir_wantagent',
        abilityName: 'EntryAbility',
        action: '',
        entities: [],
        uri: '',
        parameters: {
          targetPage: 'Index2' // 添加目标页面参数
        }
      }
    ],
    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;
    // 构造NotificationRequest对象
    let 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',
      // wantAgentObj使用前需要保证已被赋值(即步骤3执行完成)
      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.');
    });
  });
})
  1. 在EntryAbility.ets文件中添加方法实现目标UIAbility热启动目标UIAbility冷启动用来获取点击消息通知后的WantAgentInfo信息并实现跳转指定页面。
  • 热启动代码,在应用已启动的情况下实现点击消息通知后会从应用当前所在页面跳转到指定页面:
// 热启动
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  // 通过want.parameters获取参数
  const targetPage = want.parameters?.targetPage;
  console.info(`onNewWant Received parameter: ${targetPage}`)
  // 根据参数执行逻辑(例如跳转页面)
  if (targetPage === 'Index2') {
    // 跳转到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'; // 需要自行新增页面Index2来模拟跳转动作
  }
  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.');
  });
}
  1. 新增Index2页面的步骤:右键工程中的Pages文件夹,然后选择New,接着点击Page最后点击New Page,输入Index2即可创建Page页面文件Index2.ets。

  2. 模拟点击消息跳转页面步骤:

  • 冷启动:发送消息后,在多任务页面终止应用,再点击消息实现跳转应用指定页面Index2。
  • 热启动:发送消息后,将应用返回后台,再点击消息实现跳转应用指定页面Index2。

实现通知消息点击跳转到应用,需要结合WantAgent机制与页面路由能力。

1/声明通知权限

// 在EntryAbility.ts中申请通知权限

import notificationManager from '@kit.NotificationAgentKit';

notificationManager.requestEnableNotification(this.context, (err) => {

    if (err) {

        console.error('通知授权失败:', err.code);

    }

});

2/创建通知请求对象

import wantAgent from '@kit.AbilityKit';

// 构建WantAgent信息

let wantAgentInfo: wantAgent.WantAgentInfo = {

    wants: [{

        deviceId: '', // 本设备留空

        bundleName: 'com.example.app',

        abilityName: 'EntryAbility',

        parameters: { 

            targetPage: 'Index2' // 携带目标页面参数

        }

    }],

    operationType: wantAgent.OperationType.START_ABILITY

};

// 创建NotificationRequest

let notificationRequest: notificationManager.NotificationRequest = {

    content: {

        contentType: notificationManager.ContentType.NOTIFICATION_TEXT,

        normal: { title: '新消息', text: '您有未读消息' }

    },

    wantAgent: wantAgentInfo

};

3/在EntryAbility中处理跳转逻辑:

import Ability from '@ohos.app.ability.UIAbility';

import router from '@ohos.router';

export default class EntryAbility extends Ability {

    onCreate(want) {

        super.onCreate(want);

        if (want.parameters?.targetPage) {

            // 冷启动场景处理

            setTimeout(() => {

                router.pushUrl({ url: `pages/${want.parameters.targetPage}` });

            }, 500); // 延迟确保页面初始化

        }

    }

    onNewWant(want) {

        // 热启动场景处理

        if (want.parameters?.targetPage) {

            router.replaceUrl({ url: `pages/${want.parameters.targetPage}` });

        }

    }

}

在HarmonyOS Next中,通知消息点击跳转通过NotificationRequest设置WantAgent实现。开发者需在WantAgent中定义目标Ability的启动参数,包括bundleName和abilityName。点击通知时,系统根据WantAgent配置启动对应Ability或UI页面。可通过addWantAgent()方法关联通知与跳转逻辑,确保用户交互后准确导航至指定界面。

在HarmonyOS Next中,可以通过设置通知的WantAgent来实现点击通知跳转到指定应用或页面。具体步骤如下:

  1. 创建WantAgent对象,指定目标Ability(如应用主页面或特定功能页)。
  2. 构建通知时,将WantAgent绑定到通知的clickAction属性。
  3. 发送通知后,用户点击即可触发跳转。

示例代码(ArkTS):

import wantAgent from '@ohos.app.ability.wantAgent';
import notificationManager from '@ohos.notificationManager';

// 定义WantAgent参数
let wantAgentInfo: wantAgent.WantAgentInfo = {
  wants: [
    {
      bundleName: 'com.example.app',
      abilityName: 'MainAbility'
    }
  ],
  operationType: wantAgent.OperationType.START_ABILITY
};

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
  // 构建通知
  let notificationRequest: notificationManager.NotificationRequest = {
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: '通知标题',
        text: '点击跳转到应用'
      }
    },
    wantAgent: agent // 绑定点击行为
  };

  // 发布通知
  notificationManager.publish(notificationRequest);
});

注意事项:

  • 确保目标Ability的配置在module.json5中正确声明。
  • 如需传递参数,可在wants中添加parameters字段。
  • 跳转逻辑需符合HarmonyOS的Ability生命周期管理。
回到顶部