目录

serviceNotification

To enhance user services and experience, Push Kit empowers you with message subscription capabilities, enabling users to subscribe via either push tokens or user accounts. For push token–based subscriptions, you can apply for the self-classification permission for subscription messages and send corresponding subscription messages. HarmonyOS atomic services support subscription via accounts.

After selecting a subscription template for your app, you can initiate a subscription request to a user. Push Kit will then display a pop-up asking for user authorization. Only after explicit user approval can your app send messages to them using this template, thereby achieving a complete service loop.

This module provides the message subscription management capability.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Modules to Import

import { serviceNotification } from '@kit.PushKit';

serviceNotification.requestSubscribeNotification

requestSubscribeNotification(context: Context, entityIds: Array<string>, callback: AsyncCallback<RequestResult>): void

Requests authorization on message subscription. This API uses an asynchronous callback to return the result. The interval between API calls must be greater than 1 second.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Parameters:

Name Type Mandatory Description
context Context Yes Context for requesting authorization on message subscription. Only UIAbilityContext can be passed.
entityIds Array<string> Yes ID list of message templates to be subscribed to. A maximum of three IDs can be passed.
callback AsyncCallback<RequestResult> Yes Callback function triggered when the API call ends. If the operation is successful, err is undefined and data is the subscription authorization result. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401

Parameter error. Possible causes:

1. Mandatory parameters are left unspecified;

2. Incorrect parameter types;

3. Parameter verification failed.

1000900001 System internal error.
1000900008 Failed to connect to the push service.
1000900009 Internal error of the push service.
1000900010 Illegal application identity.
1000900011 The network is unavailable.
1000900017 The device does not support current operation.
1000900018 Number of calls exceeded.
1000900019 Illegal entity id.
1000900020 App token is empty.
1000900021 App is not available or not registered.
1000900022 Notification switch off.
1000900023 Number of entity ids exceed the upper limit.
1000900024 Failed to display subscription UI.
1000900025 No rights to access entity id.
1000900026 Illegal entity type.

Example:

import { UIAbility } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { serviceNotification } from '@kit.PushKit';
import { BusinessError } from '@kit.BasicServicesKit';

const LOG_DOMAIN = 0x0000;
const LOG_TAG = 'EntryAbility';

export default class EntryAbility extends UIAbility {
  async onForeground(): Promise<void> {
    hilog.info(LOG_DOMAIN, LOG_TAG, 'onForeground');

    try {
      await this.requestSubscribe();
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      hilog.error(LOG_DOMAIN, LOG_TAG, 'requestSubscribe failed, code=%{public}d, message=%{public}s', e.code, e.message);
    }
  }

  private async requestSubscribe(): Promise<void> {
    // Replace **entityIds** with the IDs of the templates to be subscribed to.
    const entityIds = ['entityId1', 'entityId2', 'entityId3'];
    serviceNotification.requestSubscribeNotification(this.context, entityIds, (err, data) => {
      if (err) {
        const e: BusinessError = err as BusinessError;
        hilog.error(LOG_DOMAIN, LOG_TAG, 'requestSubscribeNotification failed, code=%{public}d, message=%{public}s', e.code, e.message);
      } else {
        hilog.info(LOG_DOMAIN, LOG_TAG, 'requestSubscribeNotification succeeded, result=%{public}s', JSON.stringify(data.entityResult));
      }
    });
  }
}

serviceNotification.requestSubscribeNotification

requestSubscribeNotification(context: Context, entityIds: Array<string>, type?: SubscribeNotificationType): Promise<RequestResult>

Requests authorization on message subscription. This API uses a promise to return the result. The interval between API calls must be greater than 1 second.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Parameters:

Name Type Mandatory Description
context Context Yes Context for requesting authorization on message subscription. Only UIAbilityContext can be passed.
entityIds Array<string> Yes

ID list of message templates to be subscribed to. A maximum of three IDs can be passed.

If the subscription type is SUBSCRIBE_WITH_HUAWEI_ID, please refer to Selecting a Subscription Template.

type SubscribeNotificationType No Subscription type. The default value is SUBSCRIBE_WITH_TOKEN. Since: 5.0.0(12)

Returns:

Type Description
Promise<RequestResult> Promise used to return the subscription authorization result.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000900001 System internal error.
1000900008 Failed to connect to the push service.
1000900009 Internal error of the push service.
1000900010 Illegal application identity.
1000900011 The network is unavailable.
1000900017 The device does not support current operation.
1000900018 Number of calls exceeded.
1000900019 Illegal entity id.
1000900020 App token is empty.
1000900021 App is not available or not registered.
1000900022 Notification switch off.
1000900023 Number of entity ids exceed the upper limit.
1000900024 Failed to display subscription UI.
1000900025 No rights to access entity id.
1000900026 Illegal entity type.
1000900030 The user has not logged in with HUAWEI ID.

Error code 1000900030 is involved only when the API is used in an atomic service.

Error code 1000900011 may be caused by disabled network access of Push Kit. You can go to Settings -> Mobile network -> Data usage -> Network access on the phone, and check whether network access is disabled for Push Kit.

Example:

import { UIAbility } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { serviceNotification } from '@kit.PushKit';
import { BusinessError } from '@kit.BasicServicesKit';

const LOG_DOMAIN = 0x0000;
const LOG_TAG = 'EntryAbility';

export default class EntryAbility extends UIAbility {
  async onForeground(): Promise<void> {
    hilog.info(LOG_DOMAIN, LOG_TAG, 'onForeground');

    try {
      await this.requestSubscribe();
    } catch (err) {
      let e: BusinessError = err as BusinessError;
      hilog.error(LOG_DOMAIN, LOG_TAG, 'requestSubscribe failed, %{public}d %{public}s', e.code, e.message);
    }
  }

  private async requestSubscribe(): Promise<void> {
    // Replace **entityIds** with the IDs of the templates to be subscribed to.
    const entityIds = ['entityId1', 'entityId2', 'entityId3'];
    let type: serviceNotification.SubscribeNotificationType =
      serviceNotification.SubscribeNotificationType.SUBSCRIBE_WITH_HUAWEI_ID;
    serviceNotification.requestSubscribeNotification(this.context, entityIds, type).then((data) => {
      hilog.info(LOG_DOMAIN, LOG_TAG, 'requestSubscribeNotification succeeded, result=%{public}s', JSON.stringify(data.entityResult));
    }).catch((err: BusinessError) => {
      hilog.error(LOG_DOMAIN, LOG_TAG, 'requestSubscribeNotification failed, %{public}d %{public}s', err.code, err.message);
    });
  }
}

serviceNotification.querySubscribeNotificationSetting

querySubscribeNotificationSetting(): Promise<SubscribeNotificationSetting>

Queries the service notification configuration details of an atomic service.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Push.PushService

Since: 26.0.0

Returns:

Type Description
Promise<SubscribeNotificationSetting> Promise used to return the service notice configuration information of the atomic service.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

ID Error Message
1000900001 System internal error.
1000900008 Failed to connect to the push service.
1000900009 Internal error of the push service.
1000900010 Illegal application identity.
1000900011 The network is unavailable.
1000900017 The device does not support current operation.
1000900021 App is not available or not registered.
1000900030 The user has not logged in with HUAWEI ID.
1000900032 The service notification setting does not exist.

Example:

import { UIAbility } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { serviceNotification } from '@kit.PushKit';
import { BusinessError } from '@kit.BasicServicesKit';

const LOG_DOMAIN = 0x0000;
const LOG_TAG = 'EntryAbility';

export default class EntryAbility extends UIAbility {
  async onForeground(): Promise<void> {
    hilog.info(LOG_DOMAIN, LOG_TAG, 'onForeground');

    try {
      await this.querySubscribe();
    } catch (err) {
      let e: BusinessError = err as BusinessError;
      hilog.error(LOG_DOMAIN, LOG_TAG, 'querySubscribe failed, %{public}d %{public}s', e.code, e.message);
    }
  }

  /**
   * Query the service notification configuration details of an atomic service.
   */
  private async querySubscribe(): Promise<void> {
    serviceNotification.querySubscribeNotificationSetting().then((data) => {
      hilog.info(LOG_DOMAIN, LOG_TAG,
        `querySubscribeNotificationSetting succeeded, bundle: ${JSON.stringify(data.bundleName)},` +
          ` enable: ${JSON.stringify(data.enable)}, entitySettings: ${JSON.stringify(data.entitySettings)}`);
    }).catch((err: BusinessError) => {
      hilog.error(LOG_DOMAIN, LOG_TAG, 'querySubscribeNotificationSetting failed, %{public}d %{public}s', err.code, err.message);
    });
  }
}

RequestResult

Authorization result of a single subscription.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Name Type Read-Only Optional Description
entityResult Array<EntityResult> Yes No Subscription authorization result.

EntityResult

Authorization result for each message template in a single subscription.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Name Type Read-Only Optional Description
entityId string Yes No Template ID.
resultCode ResultCode Yes No Subscription authorization result code.

ResultCode

Enumerates the subscription authorization results.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 4.1.0(11)

Name Value Description
ACCEPTED 0 The user agrees to subscribe to the message of the specified template.
REJECTED 1 The user rejects to subscribe to the message of the specified template.
FILTERED 2 The template is filtered out due to duplicate template titles.
BANNED 3 The template has been removed or disabled.
UNKNOWN -1 Unknown error.

SubscribeNotificationType

Enumerate the subscription types.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since version 5.0.0(12).

System capability: SystemCapability.Push.PushService

Since: 5.0.0(12)

Name Value Description
SUBSCRIBE_WITH_TOKEN 0 Subscription via push tokens. Use this value when an app uses the push token-based subscription capability.
SUBSCRIBE_WITH_HUAWEI_ID 1 Subscription via HUAWEI IDs. Use this value when an atomic service uses the account-based subscription capability. For details, please refer to Pushing Account-based Subscription Messages.

SubscribeNotificationSetting

Service notification configuration information of an atomic service.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Push.PushService

Since: 26.0.0

Name Type Read-Only Optional Description
bundleName string No No Atomic service package name.
enable boolean No Yes Indicates whether to enable the atomic service notification function. The value true indicates yes and the value false indicates no.
entitySettings Array<EntitySetting> No Yes Service notification template information.

EntitySetting

Service notification template information.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Push.PushService

Since: 26.0.0

Name Type Read-Only Optional Description
entityId string No No Template ID.
entityName string No No Template name.
enable boolean No Yes Indicates whether the template is enabled. The value true indicates yes and the value false indicates no.
entityType EntityType No No Template type.

EntityType

Enumerate the message subscription template types.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Push.PushService

Since: 26.0.0

Name Value Description
ONCE 0 One-time message subscription template.
PERIOD 1 Long-term message subscription template.