A token uniquely identifies an app on a device. The app calls the getToken method to obtain a token from the Push Kit server. Then you can send a message to the app based on the obtained token. When no token is returned by getToken, use onNewToken to obtain one.
You are advised to upload push tokens to your app server as a list and update the list periodically. You can call the downlink message sending API of the Push Kit server to send messages in batches based on the push tokens.
public class TokenAbilitySlice extends AbilitySlice {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0xD001234,
"TokenAbilitySlice");
private void getToken() {
// Create a thread.
new Thread("getToken") {
@Override
public void run() {
try {
// Obtain the value of client_id from the agconnect-services.json file.
String appId = "your client_id";
// Set tokenScope to HCM.
String tokenScope = "HCM";
// Obtain a push token.
String token = HmsInstanceId.getInstance(getAbility().getAbilityPackage(), TokenAbilitySlice.this).getToken(appId, tokenScope);
} catch (ApiException e) {
// An error code is recorded when the push token fails to be obtained.
HiLog.error(LABEL_LOG, "get token failed, the error code is %{public}d", e.getStatusCode());
}
}
}.start();
}
} public class DemoHmsMessageServiceAbility extends HmsMessageService {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0xD001234, "DemoHmsMessageServiceAbility");
@Override
// Obtain a push token.
public void onNewToken(String token) {
HiLog.info(LABEL_LOG, "onNewToken called, token:%{public}s", token);
}
@Override
// An error code is recorded when the push token fails to be obtained.
public void onTokenError(Exception exception) {
HiLog.error(LABEL_LOG, "get onNewtoken error, error code is %{public}d", ((ZBaseException)exception).getErrorCode());
}
} Overwrite the onMessageReceived method in your service (inherited from HmsMessageService). Then you can obtain data message content as long as you send the data message to devices.
public class DemoHmsMessageServiceAbility extends HmsMessageService {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0xD001234,
"DemoHmsMessageServiceAbility");
@Override
public void onMessageReceived(ZRemoteMessage message) {
// The fields in the message content are recorded.
HiLog.info(LABEL_LOG, "get token, %{public}s", message.getToken());
HiLog.info(LABEL_LOG, "get data, %{public}s", message.getData());
ZRemoteMessage.Notification notification = message.getNotification();
if (notification != null) {
HiLog.info(LABEL_LOG, "get title, %{public}s", notification.getTitle());
HiLog.info(LABEL_LOG, "get body, %{public}s", notification.getBody());
}
}
} POST /oauth2/v3/token HTTP/1.1 Host: oauth-login.cloud.huawei.com Content-Type: application/x-www-form-urlencoded grant_type=client_credentials&client_id=<Client ID>&client_secret=<Client secret>
In the example, set Client ID and Client Secret to the client ID and client secret in OAuth 2.0 client ID of your HarmonyOS app in AppGallery Connect.
Response example:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
{
"access_token": "<Returned access token>",
"expires_in": 3600,
"token_type": "Bearer"
}
URL for calling the API using HTTPS POST:
POST https://push-api.cloud.huawei.com/v1/[clientid]/messages:send
In the URL, set [clientid] to the client ID in OAuth 2.0 client ID of your HarmonyOS app in AppGallery Connect.
Request header example:
Content-Type: application/json; charset=UTF-8 Authorization: Bearer CF3Xl2XV6jMK************************DgAPuzvNm3WccUIaDg==
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 3
}
}
},
"token": ["pushtoken1"]
}
}
The value of the token parameter in the request body is a push token. For details about the message body, please refer to en-us_topic_0000001050986197.html#EN-US_TOPIC_0000001050986197__p2316168162314.
You can customize the action triggered when a user taps the notification message, for example, opening the app home page, a website URL, or a specified app page.
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 3
}
}
},
"token": ["pushtoken1"]
}
} {
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 2,
"url":"https://www.huawei.com"
}
}
},
"token": ["pushtoken1"]
}
} {
"orientation": "unspecified",
"name": "com.test.java.MyActionAbility",
"icon": "$media:icon",
"description": "$string:myactionability_description",
"label": "$string:entry_MyActionAbility",
"type": "page",
"launchType": "standard",
"skills": [
{
"entities": ["entity.system.default"],
"actions": ["com.test.myaction"]
}
]
} You can also call the Push Kit server API to send messages. In this case, carry the click_action field, and set type to 1 (indicating to open a specified app page after message tapping) and action to the value of actions defined in the previous step.
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 1,
"action":"com.test.myaction"
}
}
},
"token": ["pushtoken1"]
}
} When sending a message, you can carry the data field in the messages. When a user taps the message, data in the data field will be transferred to the app in the specified way.
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 1,
"action":"com.test.myaction"
}
},
"data": "{'key_data':'value_data'}"
},
"token": ["pushtoken1"]
}
} public class MainAbilitySlice extends AbilitySlice {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0xD001234, "myDemo");
@Override
public void onStart(Intent intent) {
HiLog.info(LABEL_LOG, "MainAbilitySlice get started...");
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
// Call the parsing method.
parseIntent(intent);
}
private void parseIntent(Intent intent){
if (intent == null){return;}
IntentParams intentParams = intent.getParams();
if (intentParams == null) {return;}
// Obtain the key-value pair in the data field.
String key = "key_data";
Object obj = intentParams.getParam(key);
try{
// Print the key-value pair in the data field.
HiLog.info(LABEL_LOG, "my key: %{public}s, my value: %{public}s", key, obj);
}catch (Exception e){
HiLog.info(LABEL_LOG, "catch exception : " + e.getMessage());
}
}
}