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.
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).
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.
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.
(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. |
(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"
} (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"
}
}
// ...
]
}
} 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);
}
// ...
}
} 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"
]
}
]
// ...
} 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"]
}
} 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.