Location>code7788 >text

3 Steps to Easily Integrate Push Kit for App Message Pushing

Popularity:369 ℃/2024-10-10 15:29:29

Push notification, as an important messaging tool for apps, is widely used in notification scenarios in e-commerce, social media, travel and transportation. For example, when the app has new features or security patches, the system will push messages to remind users to update in time; if it is a flight travel app, the latest schedule will be sent to the user to ensure timely reminders. Push notification is an important way for apps to establish contact with users and maintain trust and satisfaction, so how can apps realize sending notification messages to users?

HarmonyOS SDKpush service(Push Kit) is a messaging push platform provided by Huawei, which establishes a messaging push channel from the cloud to the terminal. By integrating push services, HarmonyOS apps can realize real-time push notification messages to users. The display scenes mainly include notification center, lock screen, banner, desktop icon corner and notification icon.

image

business process

image

The business process of realizing push notification messages includes five steps: applying for and obtaining a Push Token, reporting the Token and other information to the application server, sending a request for a push message, sending a message to the Push Kit, and processing the message.

interpretation of nouns

Before we learn the ability to implement push notification messages, let's learn a few proper nouns.

Push Token:

Push Token identifies each application on each device. Developers call getToken() interface to request Token from Push Kit server, and after getting the Token, they need to use Push Token to push the message. When the getToken() interface is called at application startup, if the device's Token changes, the developer needs to report it to the application server in time to update the Token.

Category:

Notification message category. In order to improve the end-user push experience, Push Kit manages notification messages by category. Different values of category identify different message types, and different notification message types affect the way messages are displayed and alerted.Application Notification Message Self-Classification Interests

development step

The implementation of pushing notification messages via Push Kit is divided into three main steps, which are obtaining a Push Token, informing the user that he/she needs to be allowed to receive notification messages, and pushing the notification messages.

1. Get Push Token.

First of all, import pushService module, it is recommended to call getToken() interface in the onCreate() method of your UIAbility (e.g. EntryAbility) to get the Push Token and report it to your server, which is convenient for your server to push messages to the endpoints.

import { pushService } from '@';
//import (data)pushServicemodule (in software)。
import { hilog } from '@';
import { BusinessError } from '@';
import { UIAbility, AbilityConstant, Want } from '@';

export default class EntryAbility extends UIAbility {
  // join want together with launchParam Not used,is a parameter that comes with the project when it is initialized
  async onCreate(want: Want, launchParam: ): Promise<void> {
    // gainPush Token
    try {
      const pushToken: string = await ();
      (0x0000, 'testTag', 'Succeeded in getting push token');
    } catch (err) {
      let e: BusinessError = err as BusinessError;
      (0x0000, 'testTag', 'Failed to get push token: %{public}d %{public}s', , );
    }
    // appear in the newsPush Token并appear in the news到您的服务端
  }
}

2. The application needs to get the user's authorization to send the notification. To ensure that the application can receive the message normally, it is recommended that the application call requestEnableNotification() method before sending the notification, and then pop up the window for the user to choose whether to allow the notification to be sent or not.

import { notificationManager } from '@';
import { BusinessError } from '@';
import { hilog } from '@';
import { common } from '@';

const TAG: string = '[PublishOperation]';
const DOMAIN_NUMBER: number = 0xFF00;

let context = getContext(this) as ;
().then((data: boolean) => {
  ("isNotificationEnabled success, data: " + (data));
  if(!data){
    (context).then(() => {
      (DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification success`);
    }).catch((err : BusinessError) => {
      if(1600004 == ){
        (DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification refused, code is ${}, message is ${}`);
      } else {
        (DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification failed, code is ${}, message is ${}`);
      }
    });
  }
}).catch((err : BusinessError) => {
    (DOMAIN_NUMBER, TAG, `isNotificationEnabled fail: ${(err)}`);
});

3. The application server calls the REST API of the Push Kit server to push notification messages.

// Request URL
POST /v3/[projectId]/messages:send

// Request Header
Content-Type: application/json
Authorization: Bearer eyJr*****OiIx---****.eyJh*****iJodHR--***.QRod*****4Gp---****
push-type: 0

// Request Body
{
  "payload": {
    "notification": {
      "category": "MARKETING",
      "title": "Title of general notice",
      "body": "Contents of general notices",
      "clickAction": {
        "actionType": 0
        "data": {"testKey": "testValue"}
      },
      "notifyId": 12345
    }
  },
  "target": {
    "token": ["IQAAAA**********4Tw"]
  },
  "pushOptions": {
    "testMessage": true
  }
}

In this sample code for a push notification message, projectId is the project ID, which can be logged into theAppGallery ConnectOn the website, select "My Items", select the corresponding item in the item list, and then select "Item Settings" on the left navigation bar, and then get; push-type is 0, which means the notification message scenario; actionType is 0, which means clicking on the message to open the home page of the application.

In addition, when actionType is 1, it means that clicking the message opens the in-app customized page. If you want to realize that clicking the message opens the specified in-app page, you need to set the actions or uris value in the skills tag of the Ability to be jumped first.

An example of setting the actions parameter to finish clicking the message to enter the in-app page is shown below:

{
  "name": "TestAbility",
  "srcEntry": "./ets/abilities/",
  "exported": false,
  "startWindowIcon": "$media:icon",
  "startWindowBackground": "$color:start_window_background",
  "skills": [
    {
      "actions": [
        ""
      ]
    }
  ]
}

If you want to complete clicking a message to go to the in-app page by setting the uris parameter, the actions parameter must also be set in skills and the actions parameter must be empty.

"skills": [
  {
    "actions": [""],
    "uris": [
      {
        "scheme": "https",
        "host": "",
        "port": "8080",
        "path": "push/test"
      }
    ]
  }
]

After setting up the skills tag, when sending a message, the clickAction should carry the data field and set the actionType field to 1, then you can realize clicking the message to enter the specified in-app page.

// Request URL
POST /v3/[projectId]/messages:send

// Request Header
Content-Type: application/json
Authorization: Bearer eyJr*****OiIx---****.eyJh*****iJodHR--***.QRod*****4Gp---****
push-type: 0

// Request Body
{
  "payload": {
    "notification": {
      "category": "MARKETING",
      "title": "Title of general notice",
      "body": "Contents of general notices",
      "clickAction": {
        "actionType": 1,
        "action": "",
        "uri": ":8080/push/test",
        "data": {"testKey": "testValue"}
      }
    }
  },
  "target": {
    "token": ["IQAAAA**********4Tw"]
  },
  "pushOptions": {
    "testMessage": true
  }
}

One of the things to note is that when getting the data data passed in the message, you can get the message data data in the onCreate() method if you are clicking on the message to enter the application home page or application inner page for the first time.

import { UIAbility, Want } from '@';
import { hilog } from '@';

export default class MainAbility extends UIAbility {
  onCreate(want: Want): void {
    // Gets the value passed in the messagedatadigital
    const data = ;
    (0x0000, 'testTag', 'Succeeded in getting message data');
    // According to the actual business scenarios of thedatacarry out
   }
}

If the current application process exists, click the message to enter the application home page or application inner page, you can get the message data data in the onNewWant() method, and the onNewWant() method is only available in singleton mode.

import { UIAbility, Want } from '@';
import { hilog } from '@';

export default class MainAbility extends UIAbility {
  onNewWant(want: Want): void {
    // Gets the value passed in the messagedatadigital
    const data = ;
    (0x0000, 'testTag', 'Succeeded in getting message data');
    // According to the actual business scenario of thedatacarry out
  }
}

In the actual development process, both of the above methods need to be noted. After successfully sending the message, you can check whether the device has received the notification message, and thus the step of sending notification message via Push Kit is finished.

When pushing notification messages, there is also the possibility of user complaints or regulatory risks when the pushed notification message has errors or irregularities. For this reason, Push Kit also provides a message retraction feature to minimize the potential impact of such pushes.

It should be noted that message withdrawal only supports messages that have not been sent to the end-side, or messages that have been displayed on the end-side but have not been clicked by the user, and only supports withdrawal using Token and notifyId.

After successfully pushing a notification message, if you need to withdraw the message, you need to make sure that the application can normally receive the notification message and set the notifyId field when pushing the message, so that the application server can call the REST API to withdraw the notification message.

// Request URL 
POST /v1/[clientId]/messages:revoke
 
// Request Header 
Content-Type:application/json
Authorization:Bearer eyJr*****OiIx---****.eyJh*****iJodHR--***.QRod*****4Gp---****
push-type: 0 
 
// Request Body 
{
  "notifyId": 1234567,
  "token": [
    "pushToken1",
    "pushToken2",
    "pushToken3"
  ]
}

Here the clientId in the code needs to be replaced with the Client ID of the application, and the way to get it is the same as projectId. notifyId is used as the message ID, which is the unique identifier of the message.

With the above steps, we can push and withdraw general notification messages through Push Kit. On the basis of this ability, we can also continue to explore more personalized service capabilities of Push Kit to create more possibilities for the application of pulling new and promoting activities.

Learn more >>

interviewsPush Service Alliance Official Website

gainPush Notification Messaging Development Guidance Document