目录

Sending a Text-to-Speech Message

Use Cases

When a user device receives a text-to-speech message sent by you:

Constraints

The function of pushing text-to-speech messages supports phones, tablets, and PCs/2-in-1 devices. Support for wearables is available starting from 5.1.0(18), and for TVs starting from 6.1.0(23).

Applying for Required Permissions

You need to apply for the text-to-speech message permission to push text-to-speech messages to your users.

Frequency Control

During the debugging phase, the maximum number of test messages that can be pushed for each project every day is 1000. To send test messages, you need to set testMessage to true.

After formal release, the total number of messages that each app can push to a single device each day is subject to the device-based message frequency control policy. The message sending frequency is governed based on service scenarios and traffic. In cases where message sending is unnecessary or unreasonable, frequency limits will be applied.

Development Procedure

  1. Obtain a push token.

  2. To ensure that devices can receive messages properly, you are advised to call the requestEnableNotification() method to prompt users to allow notifications before sending messages. For details, please refer to Requesting Notification Authorization of Notification Kit.

  3. Call the REST API provided by Push Kit on your app server to send a message. For details, please refer to the function description for the API used to push scenario-specific messages. The following is a request example:

    // Request URL
    POST "https://push-api.cloud.huawei.com/v3/[projectId]/messages:send"
     
    // Request header
    Content-Type: application/json
    Authorization: Bearer eyJr*****OiIx---****.eyJh*****iJodHR--***.QRod*****4Gp---****
    push-type: 2
    
    // Request body
    {
      "payload": {
        "extraData": "{\"title\":\"replace title\",\"text\":\"replace text\"}",
        "notification": {
          "category": "PLAY_VOICE",
          "title": "Notification title",
          "body": "Notification body",
          "image":"https://lf*******246.png",
          "clickAction": {
            "actionType": 0
          },
          "notifyId": 12345
        }
      },
      "target": {
        "token": ["MAMzLg**********lPW"]
      },
      "pushOptions": {
        "testMessage": true,
        "ttl": 86400
      }
    }
    • [projectId]: project ID. To obtain the value, sign in to AppGallery Connect, click Development and services, click the desired project, and go to Project settings.

    • Authorization: a character string in JWT format. Obtain the value by referring to Authorization.

    • push-type: The value 2 indicates the text-to-speech message type.

    • category: message category used for self-classification. Currently, this parameter can be set to PLAY_VOICE.

    • actionType: action triggered upon message tapping. The value 0 indicates that the home screen of the app will be opened after a user taps the message.

    • token: push token. Obtain the value by referring to Obtaining a Push Token.

    • extraData: extra data carried, which is a character string. For details, please refer to ExtensionPayload (Text-to-Speech Message). For details about how to obtain extraData, please refer to the sample code.

    • testMessage (optional): indicates whether a message is a test message. The value true indicates a test message. In each project, a maximum of 1000 test messages can be sent every day. Each push can carry up to 10 tokens. For details, please refer to testMessage.

    • ttl (optional): message cache duration. For details, please refer to ttl.

    • notifyId (optional): custom message ID. If a message does not contain the ID or the ID is -1, Push Kit will generate a unique ID for the message. Different notification messages can use the same message ID, so that new messages can overwrite old messages. The ID must be a number in the range [0, 2147483647]. If the ID will be used for message recall, it must be set. For details, please refer to notifyId.

    • image (optional): URL of the large icon on the right of a notification. The URL must use the HTTPS protocol.

    Do not push images that contain sensitive content.

  4. Implement the following logic: If your app is not in the foreground when a message is sent by calling the REST API, Push Kit will deliver the notification content to the notification extension process, and the app process returns the customized notification content (including the title and body fields). Push Kit will then display the customized notification in the notification panel. The detailed procedure is as follows:

    Set type and actions for RemoteNotificationExtAbility in the extensionAbilities section of the src/main/module.json5 file under your project. There shall be only one ExtensionAbility for defining type and actions. If the uris parameter also exists, it should be left empty. The following is a configuration example:

    "extensionAbilities": [
      // ...
      {
        "name": "RemoteNotificationExtAbility",
        "type": "remoteNotification",
        "srcEntry": "./ets/entryability/RemoteNotificationExtAbility.ets",
        "description": "RemoteNotificationExtAbility test",
        "exported": false,
        "skills": [
          // Add an independent skill object and set the actions parameter.
          {
            "actions": [
              "action.hms.push.extension.remotenotification"
            ]
          }
        ]
      }
      // ...
    ]
    • type: The value is always remoteNotification, indicating the ExtensionAbility type for notification extension.
    • actions: The value is always action.hms.push.extension.remotenotification, indicating that text-to-speech messages will be received.

    Create an ExtensionAbility component in your project, which inherits RemoteNotificationExtensionAbility. Override the onReceiveMessage() method for data reception and service processing. The sample code is as follows:

    import { pushCommon, RemoteNotificationExtensionAbility } from '@kit.PushKit';
    import { image } from '@kit.ImageKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { resourceManager } from '@kit.LocalizationKit';
    import { common } from '@kit.AbilityKit';
    
    const DOMAIN = 0x0000;
    
    export default class RemoteNotificationExtAbility extends RemoteNotificationExtensionAbility {
      async onReceiveMessage(remoteNotificationInfo:pushCommon.RemoteNotificationInfo): Promise<pushCommon.RemoteNotificationContent> {
        hilog.info(DOMAIN, 'testTag', 'RemoteNotificationExtAbility onReceiveMessage, notifyId: %{public}d', remoteNotificationInfo.id);
    
        // Create a PixelMap object based on image decoding parameters.
        const resourceMgr: resourceManager.ResourceManager = (this.context as common.UIExtensionContext).resourceManager;
        let fileData: Uint8Array = new Uint8Array(0);
        try {
          fileData = await resourceMgr.getMediaContent($r('app.media.startIcon').id);
        } catch (e) {
          hilog.error(DOMAIN, 'testTag', 'Failed to get media content: %{public}d %{public}s', e.code, e.message);
        }
        const buffer = fileData.buffer;
        const imageSource: image.ImageSource = image.createImageSource(buffer as ArrayBuffer);
        const pixelMap: image.PixelMap = await imageSource.createPixelMap();
        if (pixelMap) {
          pixelMap.getImageInfo((err, imageInfo) => {
            if (imageInfo) {
              hilog.info(DOMAIN, 'testTag', `imageInfo ${imageInfo.size.width} * ${imageInfo.size.height}`);
            } else {
              hilog.error(DOMAIN, 'testTag', `Failed to obtain the image information.code is ${err.code}, message is ${err.message}`);
            }
          });
        }
    
        // You need to implement the logic of voice broadcast for your app yourself.
        this.textToSpeech();
    
        // Return the content displayed in the extended message.
        return {
          title: 'Default replace title.',
          text: 'Default replace text.',
          badgeNumber: 1,
          setBadgeNumber: 2,
          overlayIcon: pixelMap,
          wantAgent: {
            abilityName: 'DemoAbility',
            parameters: {
              key: 'Default value'
            }
          }
        }
      }
    
      textToSpeech(): void {
        // Implement the logic of voice broadcast.
      }
    
      onDestroy(): void {
        hilog.info(DOMAIN, 'testTag', 'RemoteNotificationExtAbility onDestroy.');
      }
    }
    • The return value of the function will be used to replace the notification to be displayed on devices. title and text indicate the notification title and body to be displayed respectively.

    • The badgeNumber field specifies the increment to be added to the current badge number. The setBadgeNumber field determines the exact badge number to be displayed. If both fields are present, setBadgeNumber takes precedence over badgeNumber. For details, please refer to RemoteNotificationContent.

    • The overlayIcon field specifies the superimposed icon of the displayed notification. For details, please refer to RemoteNotificationContent.

    • The wantAgent.abilityName field indicates the abilityName to be replaced (for example, DemoAbility), corresponding to the landing page to be opened upon message tapping. You need to develop and adapt the DemoAbility by yourself. For details, please refer to RemoteWantAgent.

    • The wantAgent.parameters field indicates the data to be transferred to the app. For details, please refer to RemoteWantAgent.

      You can implement voice broadcast using the textToSpeech() method in the sample code.

      You can implement voice broadcast by using the following capabilities offered by diverse kits:

  5. Implement the following logic: If your app is in the foreground when a message is sent by calling the REST API, Push Kit will not display the notification on the notification panel. The detailed procedure is as follows:

    Set actions to action.ohos.push.listener in skills of the abilities section in the src/main/module.json5 file at the module level. (This action can be defined for only one ability. If the uris parameter also exists, it should be left empty.) The following sample code uses PushMessageAbility as an example:

    {
      "name": "PushMessageAbility",
      "srcEntry": "./ets/abilities/PushMessageAbility.ets",
      "description": "$string:PushMessageAbility_desc",
      "icon": "$media:layered_image",
      "label": "$string:PushMessageAbility_label",
      "startWindowIcon": "$media:startIcon",
      "startWindowBackground": "$color:start_window_background",
      "launchType": "singleton",
      "exported": false,
      "skills": [
        // Keep the existing skill object unchanged.
        {
          "actions": [
            "com.app.action"
          ]
        },
        // Add an independent skill object and set the actions parameter.
        {
          "actions": [
            "action.ohos.push.listener"
          ]
        }
      ]
    // ...
    }

    In the onCreate() method of the existing UIAbility class in the client-side project, call the receiveMessage() method and set PushType to IM to obtain text-to-speech messages when the app is running in the foreground. The following sample code uses PushMessageAbility as an example:

    Import the pushService module and related common modules:

    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
    import { pushService } from '@kit.PushKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';

    Call the receiveMessage API to receive scenario-specific messages from Push Kit.

    const DOMAIN = 0x0000;
    
    export default class PushMessageAbility extends UIAbility {
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        // ...
        try {
          pushService.receiveMessage('IM', this, (payload) => {
            hilog.info(DOMAIN, 'testTag', '%{public}s', 'receive message for IM type');
    
            try {
              const data: string = payload?.data;
              // Process data.
              hilog.info(DOMAIN, 'testTag', 'Succeeded in getting notification, data=%{public}s',
                JSON.stringify(JSON.parse(data)?.notification));
            } catch (err) {
              const e: BusinessError = err as BusinessError;
              hilog.error(DOMAIN, 'testTag', 'Failed to process data: %{public}d %{public}s', e.code, e.message);
            }
          });
          hilog.info(DOMAIN, 'testTag', '%{public}s', 'Succeeded in registering IM message');
        } catch (err) {
          const e: BusinessError = err as BusinessError;
          hilog.error(DOMAIN, 'testTag', 'Failed to register IM message: %{public}d %{public}s', e.code, e.message);
        }
      }
      // ...
    }