目录

发起基于账号的订阅请求

场景介绍

元服务选用服务通知模板后,主动向登录华为账号的用户发起订阅请求,Push Kit将向用户弹出授权弹窗。当用户在弹窗中选择后,Push Kit将返回用户的订阅选择给元服务,元服务根据用户的订阅结果处理消息下发逻辑。

Push Kit当前仅支持一次性订阅模板。

频控规则

单设备单元服务下,发起订阅请求的次数不应大于每5分钟30次,若在5分钟内超过30次会进入频控状态,限制调用订阅接口。超过5分钟后频控重置。

弹窗效果

弹窗样式请参考如下示例:

弹窗中包含以下信息:

其中用户授权订阅按钮分为“允许”和“禁止”:

开发指导

  1. 开始开发前,请先确保已完成开发准备中的配置,同时开通服务通知并选用订阅模板。
  2. 元服务调用serviceNotification.requestSubscribeNotification()方法发起消息订阅,示例如下:

    import { UIAbility } from '@kit.AbilityKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { window } from '@kit.ArkUI';
    import { serviceNotification } from '@kit.PushKit';
     
    export default class EntryAbility extends UIAbility {
      onWindowStageCreate(windowStage: window.WindowStage): void {
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
        windowStage.loadContent('pages/Index', (err) => {
          if (err.code) {
            hilog.error(0x0000, 'testTag', 'Failed to load the page. Cause: %{public}s', JSON.stringify(err) ?? '');
            return;
          }
          hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
        });
      }
    
      async requestSubscribeNotification() {
        try {
          // entityIds请替换为待订阅的模板ID
          let entityIds: string[] = ['13B6000E24008000', '13B90C82D3802680'];
          let type: serviceNotification.SubscribeNotificationType =
            serviceNotification.SubscribeNotificationType.SUBSCRIBE_WITH_HUAWEI_ID;
          const res: serviceNotification.RequestResult =
            await serviceNotification.requestSubscribeNotification(this.context, entityIds, type);
          hilog.info(0x0000, 'testTag', 'Succeeded in requesting serviceNotification: %{public}s',
            JSON.stringify(res.entityResult));
        } catch (err) {
          let e: BusinessError = err as BusinessError;
          hilog.error(0x0000, 'testTag', 'Failed to request serviceNotification: %{public}d %{public}s', e.code, e.message);
        }
      }
     
      async onForeground(): Promise<void> {
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
        try {
          // 请确保加载页面完成,可以获取UIAbilityContext后调用方法
          await this.requestSubscribeNotification();
        } catch (err) {
          let e: BusinessError = err as BusinessError;
          hilog.error(0x0000, 'testTag', 'Request subscribe notification failed: %{public}d %{public}s', e.code, e.message);
        }
      }
    }
    • entityIds:订阅模板的id,请使用在服务通知中选用的模板ID。单次可订阅模板最多不超过3个。
    • type:订阅类型,元服务仅支持基于账号订阅,固定类型为SUBSCRIBE_WITH_HUAWEI_ID。详情见SubscribeNotificationType。
    • res:订阅成功后返回的结果。详情见RequestResult。

  3. 当用户同意订阅(ResultCode的值为0),元服务可基于账号推送消息,详情见推送基于账号的订阅消息。