目录

Pushing a Background Message

Use Cases

Background messages are for scenarios where content updates are not frequent. They operate discreetly, without the usual notifications, ringtones, or app badge number changes. Upon receiving a background message, the device will transfer the message to the app if the app is currently running in the foreground. Otherwise, the message will be cached for later delivery after the app is launched.

The device caches only the latest message for up to seven days by default.

Constraints

The function of pushing background 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 5.1.1(19).

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.

  • Background messages are of a lower priority. To ensure delivery, it is advisable to limit background message frequency to no more than two per hour.

  • Factors such as the device battery level, system sleep, and user interactions can affect the timely delivery of background messages.

Development Procedure

You can choose a message cache policy based on your needs when the app process is not running in the foreground:

  • If you only need to cache the latest message on the device, you can skip step 2 to step 4.

  • If you want to cache more messages on the device, complete step 2 to step 4 to develop and adapt an on-device database and enable proxy-based data writing to the database. Push Kit will write background messages to the database. After your app process is launched in the foreground, it will read messages from the database by itself.

  1. Obtain a push token.

  2. (Optional) Create an on-device database (for example, pushmessage.db) by referring to the guide and create a table (for example, t_push_message) exactly in the following format.

    Field Type Description
    id INTEGER Auto-increment primary key.
    message_id TEXT Message ID.
    push_type TEXT Scenario type.
    message_action INTEGER Message action.
    message TEXT Message content.
    field1 TEXT Extended field 1.
    field2 TEXT Extended field 2.
    field3 TEXT Extended field 3.
    field4 TEXT Extended field 4.
    field5 TEXT Extended field 5.
    create_time INTEGER Timestamp when a message is written to the database, in milliseconds.
  3. (Optional) Create the PushMessage.json file under src/main/resources/base/profile/ at the module level. The file content is as follows:

    {
      "path": "pushmessage/t_push_message",
      "type": "rdb",
      "scope": "application"
    }
    • path: path of the table created in step 2, in the format [Database name]/[Table name], for example, pushmessage/t_push_message.
    • type: The value is always rdb, indicating a relational database.
    • scope: database level. The options are application (app-level) and module (HAP module-level).
  4. (Optional) Add the following proxyData configuration to the src/main/module.json5 file under the module-level directory of your project:

    {
      "module": {
        // ...
        "proxyData": [
          {
            "uri": "datashareproxy://{bundleName}/PushMessage",
            "requiredWritePermission": "ohos.permission.WRITE_PRIVACY_PUSH_DATA",
            "metadata": {
              "name": "dataProperties",
              "resource": "$profile:PushMessage"
            }
          }
          // ...
        ]
      }
    }
    • uri: The value is in format datashareproxy://{bundleName}/PushMessage. You need to replace {bundleName} with the bundle name of your app. PushMessage is a fixed value and cannot be changed.
    • requiredWritePermission: The value is always ohos.permission.WRITE_PRIVACY_PUSH_DATA, which allows Push Kit to write background message data to the database.
    • metadata: extended configuration. The value of name is fixed to dataProperties. The value of resource must be in the format $profile:File name. The file name should be PushMessage.
  5. In the onCreate() method of the existing UIAbility class in your project, call the receiveMessage() method to receive background messages. The following sample code uses PushMessageAbility as an example. Note that you can only use UIAbility to receive background messages.

    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
    import { pushCommon, pushService } from '@kit.PushKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    // ...
    
    const DOMAIN = 0x0000;
    
    export default class PushMessageAbility extends UIAbility {
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        // ...
        try {
          pushService.receiveMessage('BACKGROUND', this, (data: pushCommon.PushPayload) => {
            // Process the message.
            try {
              hilog.info(DOMAIN, 'testTag', 'Receive background message : %{public}s', JSON.stringify(data));
            } catch (e) {
              let errRes: BusinessError = e as BusinessError;
              hilog.error(DOMAIN, 'testTag', 'Failed to process data: %{public}d %{public}s', errRes.code, errRes.message);
            }
          });
        } catch (err) {
          let e: BusinessError = err as BusinessError;
          hilog.error(DOMAIN, 'testTag', 'Failed to get background message: %{public}d %{public}s', e.code, e.message);
        }
        // ...
      }
    }
  6. Set actions to action.ohos.push.listener in skills in the abilities section of the src/main/module.json5 file at the project level. (This action can be defined for only one ability. If the uris parameter also exists, it should be left empty.)

    {
      "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"
          ]
        }
      ]
    // ...
    }
  7. Call the REST API provided by Push Kit on your app server to send a background 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: 6
    
    // Request body
    {
      "payload": {
        "extraData": "Extra data carried",
        "proxyData": "ENABLE"
      },
      "target": {
        "token": ["MAMzLg**********lPW"]
      }
    }
    • [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 6 indicates the background message type.
    • 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 extraData.
    • proxyData (optional): indicates whether to enable the data proxy to silently write data to the app cache when the process does not exist. Currently, the value can only be ENABLE to enable the proxy. If you do not want to enable the proxy to write data, do not set this parameter in the message body. For details, please refer to proxyData.

    When the app process is running in the foreground, the app is directly launched to transfer message data. You can call the receiveMessage() method to obtain message data.

    When the app process is not running in the foreground and proxyData is set to ENABLE, Push Kit writes background message data to the database. You are advised to migrate the data from the database to your own service database once your app process is launched in the foreground to prevent unlimited database growth. When the app process is not running in the foreground and proxyData is not set, messages are cached. (If multiple messages are sent, only the latest message is cached.) Once the app process is later launched in the foreground, call the getToken API so Push Kit will send the cached message again. You can call the receiveMessage method to obtain the message data.