Initialize and add the SDK
Prerequisites
The push service for the application is enabled on the Huawei AppGallery Connect platform. For more information, see Huawei Push Kit.
Before you add the Message Push software development kit (SDK), make sure that you have added mPaaS to your project. For more information, see Add mPaaS capabilities.
Component integration
Call the method in the
onCreatemethod of theAbility.The following is the code:
import { MpaasPushServiceImpl, MPPush, CallResp } from '@mpaas/push'; let tokenGet: CallResp try { tokenGet = await MPPush.init() console.info("CallResp="+tokenGet) if (tokenGet.success) { this.tokenVal = tokenGet.msg } else { console.info("MPPush.init failed=" + tokenGet.msg) } } catch (e) { console.info("MPPush.init err=" + e.message) }This method initializes the
Pushservice component, obtains a HarmonyOS pushtoken, and reports the token to the server.If the call is successful, the method returns the
tokenvalue.If the call fails, the method returns an empty string and logs the failure.
Create an
Abilityto host the MPS component that inherits fromMpaasNcAbility.The code is as follows:
export default class MpaasBridgeMsgAbility extends MpaasNcAbility { static tag: string = "MpaasBridgeMsgAbility" onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(0x0000, MpaasBridgeMsgAbility.tag, "start MpaasBridgeMsgAbility onCreate") super.onCreate(want, launchParam) } onForeground() { console.log('MpaasBridgeMsgAbility onBackground'); } }Note:
In SDKs with a baseline version of 10.2.3.13 or later, the configuration page is automatically destroyed within
NcAbility. You do not need to implement this action.If the baseline version is earlier than 10.2.3.13, the developer must add the
this.context.terminateSelfcode to theonForegroundmethod of the configuration page. The following code shows a configuration example:import { MpaasNcAbility } from '@mpaas/push' export default class MpaasBridgeMsgAbility extends MpaasNcAbility { static tag: string = "MpaasBridgeMsgAbility" onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(0x0000, MpaasBridgeMsgAbility.tag, "start MpaasBridgeMsgAbility onCreate") super.onCreate(want, launchParam) } onForeground() { console.log('MpaasBridgeMsgAbility onBackground'); try { // Destroy the intermediate transition Ability. this.context.terminateSelf((err: BusinessError) => { if (err.code) { // Handle business logic errors. console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); return; } // Execute normal business logic. console.info('terminateSelf succeed'); }); } catch (err) { // Catch synchronous parameter errors. let code = (err as BusinessError).code; let message = (err as BusinessError).message; console.error(`terminateSelf failed, code is ${code}, message is ${message}`); } } }ImportantIf you upgrade the client component to version 10.2.3.13 or later and do not remove this destroy code, the redirection action will fail.
In the
module.json5file, declareMpaasBridgeMsgAbility.The following is the code:
{ "name": "MpaasBridgeMsgAbility", "srcEntry": "./ets/pushability/MpaasBridgeMsgAbility.ets", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:BridgeAbility_label", "startWindowIcon": "$media:startIcon", "startWindowBackground": "$color:start_window_background", "exported": true, "removeMissionAfterTerminate": true, "skills": [ { "actions": ["com.mpaas.harmony.push"] } ] }NoteThe value of
actionsmust be consistent with its declaration in the code.The
removeMissionAfterTerminatefield must be set totrue. Otherwise,MpaasBridgeMsgAbilityis not completely destroyed. This results in an extra and invalidUIAbilityin the application.
ImportantIf you have upgraded HarmonyOS Push by following the instructions in Update and adapt the push feature, you do not need to configure
MpaasBridgeMsgAbility.
Use the SDK
Before you use the SDK, make sure that you have set the userId at the framework layer.
The following code shows how to perform subsequent token binding, unbinding, and pushes.
MPFramework.instance.userId = "mpaas_push"Bind or unbind a token
To bind a token, call the binding API to send the application's user ID and token to the backend. Unbinding cancels the binding.
The following is the binding API:
import { MpaasPushServiceImpl, MPPush, CallResp } from '@mpaas/push'; // The first input parameter: mobile number. If no mobile number is available, enter "". This parameter is required. // The second input parameter: token, which is the token value returned by the init method. This parameter is required. // The third input parameter: userid. This parameter is optional. If you do not specify this parameter, the userId set at the MPFramework layer is used. let res: CallResp = await MpaasPushServiceImpl.getInstance().bind("12345678900", this.tokenVal, "push_userid") console.log("bind res="+res.msg) if (res.success) { this.bindState = "bind state: " + "binded" }The return value
res.successindicates whether the binding is successful.The following is the unbinding API:
import { MpaasPushServiceImpl, MPPush, CallResp } from '@mpaas/push'; // The first input parameter: token, which is the token value returned by the init method. This parameter is required. // The second input parameter: userid. This parameter is optional. If you do not specify this parameter, the userId set at the MPFramework layer is used. let res: CallResp = await MpaasPushServiceImpl.getInstance().unbind(this.tokenVal) console.log("unbind res="+res.msg) if (res.success) { this.bindState = "bind state: " + "unbind" }The return value
res.successindicates whether the unbinding is successful.
Configure the message redirection Ability
In the client's module.json5 file, configure the target Ability in the application, such as the following PushLandingAbility:
{
"name": "PushLandingAbility",
"srcEntry": "./ets/pushability/PushLandingAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:LandingAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"actions": [""],
"uris": [
{
"scheme": "jump",
"host": "com.mpaas.harmony.push",
"path": "landing"
}
]
}
]
}When you push a message from the console, set the redirection URI to jump://com.mpaas.harmony.push/landing. This URI corresponds to the uris in the preceding code. After the message is pushed from the console, you can tap the notification on the client to navigate to the page that corresponds to the configured PushLandingAbility.
If the server-side version is 1.35.0 or later and the client baseline version is 10.2.3.13 or later, tapping a notification will not open an HTTP link in a browser. Only custom redirection links are supported. You must implement the web page redirection yourself.
Example code for configuring the landing page Ability
import { MPPushMsg,PushMsgHandler,msgOutput,MpaasPushServiceImpl } from '@mpaas/push';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import window from '@ohos.window';
import hilog from '@ohos.hilog';
import pushService from '@hms.core.push.pushService';
import { BusinessError } from '@ohos.base';
export class PushLandingAbility extends UIAbility {
private TAG: string = "PushLandingAbility"
public para: Record<string,string> = { 'msg_id': "default", 'msg_data': "default"};
public storageData: LocalStorage = new LocalStorage(this.para);
landingWindowStage: window.WindowStage | undefined = undefined;
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
super.onCreate(want, launchParam)
// When the client baseline version is 10.2.3.13 or later and the server-side MPS version is 1.35.0 or later,
// you can use the PushMsgHandler.parsePushMsg tool to parse messages.
let msg: msgOutput | undefined = PushMsgHandler.parsePushMsg(want)
let msg_id: string | undefined = msg?.msg_id
let msg_data: MPPushMsg | undefined = msg?.msg_data
if (msg) {
if (msg_id) {
k = msg_id
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate k: %{public}s', k);
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg_id is undefined');
}
if (msg_data) {
v = msg_data
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate v: %{public}s', k);
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg_data is undefined');
}
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg is undefined');
}
this.storageData.set('msg_id', k)
this.storageData.set('msg_data', JSON.stringify(v))
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate push_msgkey: %{public}s', k);
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate push_msgdata: %{public}s', JSON.stringify(v));
}
async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
hilog.info(0x0000, PushLandingAbility.TAG, 'PushLandingAbility onNewWant. Data: %{public}s', JSON.stringify(want.parameters) ?? '');
let k: string = ""
let v: object = JSON.parse("{}")
// When the client baseline version is 10.2.3.13 or later and the server-side MPS version is 1.35.0 or later,
// you can use the PushMsgHandler.parsePushMsg tool to parse messages.
let msg: msgOutput | undefined = PushMsgHandler.parsePushMsg(want)
let msg_id: string | undefined = msg?.msg_id
let msg_data: MPPushMsg | undefined = msg?.msg_data
if (msg) {
if (msg_id) {
k = msg_id
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate k: %{public}s', k);
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg_id is undefined');
}
if (msg_data) {
v = msg_data
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate v: %{public}s', k);
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg_data is undefined');
}
} else {
hilog.warn(0x0000, PushLandingAbility.TAG, 'msg is undefined');
}
// this.para = { 'msg_key': this.pushKey, 'msg_data': JSON.stringify(this.pushData)};
this.storageData.set('msg_id', k)
this.storageData.set('msg_data', JSON.stringify(v))
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant push_msgkey: %{public}s', this.storageData.get("msg_id"));
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant push_msgdata: %{public}s', JSON.stringify(this.storageData.get("msg_data")));
if (this.landingWindowStage != null) {
hilog.info(0x0000, PushLandingAbility.TAG, 'start landingWindowStage.loadContent');
await this.landingWindowStage.loadContent('pushpages/pushLandingPage', this.storageData)
}
}
onDestroy(): void {
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onDestroy');
}
async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
// Main window is created, set main page for this ability.
// Create a new instance and initialize it with the given object.
this.landingWindowStage = windowStage
hilog.info(0x0000, PushLandingAbility.TAG, 'this.pushKey= %{public}s',this.storageData.get("msg_id"));
hilog.info(0x0000, PushLandingAbility.TAG, 'this.pushData= %{public}s',this.storageData.get("msg_data"));
try {
hilog.info(0x0000, PushLandingAbility.TAG, 'this.storageData. Key: %{public}s, this.storageData Data: %{public}s',this.storageData.get("msg_id"), this.storageData.get("msg_data"));
await windowStage.loadContent('pushpages/pushLandingPage', this.storageData)
hilog.info(0x0000, PushLandingAbility.TAG, 'Succeeded in loading the content. Key: %{public}s, Data: %{public}s',this.storageData.get("msg_id"), JSON.stringify(this.storageData.get("msg_data")) ?? '');
} catch (e) {
console.log("err msg="+e.message)
return
}
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources.
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground.
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background.
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onBackground');
}
}To use this message parsing method, you must upgrade the server-side baseline and the client-side MPS version. Ensure that the server-side MPS version is 1.35.0 or later and the client baseline version is 10.2.3.13 or later.
msg_id corresponds to the message ID, and msg_data corresponds to the message data.
Note:
If the preceding version requirements are not met, continue to use the original message parsing method.
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import window from '@ohos.window';
import hilog from '@ohos.hilog';
import { MpaasPushServiceImpl } from '@mpaas/push';
import pushService from '@hms.core.push.pushService';
import { BusinessError } from '@ohos.base';
export class PushLandingAbility extends UIAbility {
private static TAG: string = "PushLandingAbility"
private pushData: object = JSON.parse("{}");
private pushKey: string = "";
public para: Record<string,string> = { 'msg_id': "default", 'msg_data': "default"};
public storageData: LocalStorage = new LocalStorage(this.para);
landingWindowStage: window.WindowStage | undefined = undefined;
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
hilog.info(0x0000, PushLandingAbility.TAG, 'PushLandingAbility create. Data: %{public}s', JSON.stringify(want.parameters) ?? '');
let k: string = ""
let v: object = JSON.parse("{}")
if (want.parameters) {
if (want.parameters["msg_id"]) {
k = want.parameters["msg_id"] as string
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant k: %{public}s', k);
}
if (want.parameters["msg_data"]) {
v = want.parameters["msg_data"]
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant k: %{public}s', v);
}
}
this.storageData.set('msg_id', k)
this.storageData.set('msg_data', JSON.stringify(v))
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate push_msgkey from storage: %{public}s', this.storageData.get("msg_id"));
hilog.info(0x0000, PushLandingAbility.TAG, 'onCreate push_msgdata from storage: %{public}s', JSON.stringify(this.storageData.get("msg_data")));
}
async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
let k: string = ""
let v: object = JSON.parse("{}")
if (want.parameters) {
if (want.parameters["msg_id"]) {
k = want.parameters["msg_id"] as string
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant k: %{public}s', k);
}
if (want.parameters["msg_data"]) {
v = want.parameters["msg_data"]
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant k: %{public}s', v);
}
}
this.storageData.set('msg_id', k)
this.storageData.set('msg_data', JSON.stringify(v))
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant push_msgkey: %{public}s', this.storageData.get("msg_id"));
hilog.info(0x0000, PushLandingAbility.TAG, 'onNewWant push_msgdata: %{public}s', JSON.stringify(this.storageData.get("msg_data")));
// At this stage, you need to manually load the page.
if (this.landingWindowStage != null) {
await this.landingWindowStage.loadContent('pushpages/pushLandingPage', this.storageData)
}
}
onDestroy(): void {
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onDestroy');
}
async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
// Main window is created, set main page for this ability.
// Create a new instance and initialize it with the given object.
this.landingWindowStage = windowStage
hilog.info(0x0000, PushLandingAbility.TAG, 'this.pushKey= %{public}s',this.storageData.get("msg_id"));
hilog.info(0x0000, PushLandingAbility.TAG, 'this.pushData= %{public}s', JSON.stringify(this.storageData.get("msg_data")));
try {
await windowStage.loadContent('pushpages/pushLandingPage', this.storageData)
hilog.info(0x0000, PushLandingAbility.TAG, 'Succeeded in loading the content. Key: %{public}s, Data: %{public}s',this.storageData.get("msg_id"), JSON.stringify(this.storageData.get("msg_data")) ?? '');
} catch (e) {
console.log("err msg="+e.message)
return
}
}
onWindowStageDestroy(): void {
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onForeground');
}
onBackground(): void {
hilog.info(0x0000, PushLandingAbility.TAG, '%{public}s', 'Ability onBackground');
}
}Configure the pass-through message Ability
The backend can push background messages to the client application without displaying them in the notification bar. However, developers can still use specific methods to retrieve the pushed data. MPS supports background messages that can be processed without starting a child process for the application.
Inherit the
MpaasExtDefaultNcAbilityclass to implement your ownAbility, as shown below:import { MpaasExtDefaultNcAbility, PushExtConstants } from '@mpaas/push' import emitter from '@ohos.events.emitter'; let innerEvent: emitter.InnerEvent = { eventId: PushExtConstants.BACKGROUD_MSG_EVENT_ID }; export default class MpaasBridgeExtMsgAbility extends MpaasExtDefaultNcAbility { async onCreate(): Promise<void> { // Execute the callback function after receiving an event with eventId 9999. emitter.on(innerEvent, (data) => { if (data.data != null) { console.log("onCreate receivedMsg="+JSON.stringify(data.data["receivedMsg"])) } else { console.log("onCreate receivedMsg="+data.data) } }); await super.onCreate() } }In the
onCreate()method, executesuper.onCreate(). Then, you can callMpaasExtDefaultNcAbility.getReceivedMsg()to retrieve the background push message.Configure
MpaasBridgeExtMsgAbilityin themodule.json5file, as shown below:{ "name": "MpaasBridgeExtMsgAbility", "srcEntry": "./ets/pushability/MpaasBridgeExtDeMsgAbility.ets", "launchType": "singleton", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:start_window_background", "skills": [ { "actions": [ "action.ohos.push.listener" ] } ] }In
skills, set the value ofactionstoaction.ohos.push.listener.ImportantOne and only one
abilitycan define theaction. If theurisparameter is also specified, the value ofurismust be empty.
Clear the badge count
You can call the method provided by MPS to clear the application's badge count when the application is opened. The method is as follows:
BadgeUtil.clearBadge()