We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
GuidesPush KitAndroidBasic CapabilitiesObtaining and Deleting a Push Token

Obtaining and Deleting a Push Token

Obtaining a Push Token

Scenario Description

A token uniquely identifies an app on a device. An app can call the getToken method to request a token from the Push Kit server. If no token is returned by getToken, the onNewToken method can be used to obtain one. Therefore, you need to implement the onNewToken method. Alternatively, you can use automatic initialization of the Push SDK to automatically obtain a token. After obtaining a token, your app needs to report it to your app server. Then, you can call the downlink message sending API to send messages based on the token.

The token is only relevant to your app ID and is irrelevant to the HUAWEI ID. Therefore, the token will not be changed after HUAWEI ID change. You are advised to use account verification of Push Kit to develop account-related functions, without needing to use a push token.

Generally, the token changes only in the following scenarios. Therefore, do not request tokens frequently, especially for apps running in the background.

  • The app is re-launched after app data is cleared (when the app is reinstalled, when the device is restored to its factory settings, or in other scenarios).
  • The app explicitly calls the method for deleting a push token and then calls the getToken method.
NOTE

To improve security, Push Kit updated token encoding rules in November of 2020. If a user updates the Push Service app to the new version, after the user reinstalls your app and launches it, the token that your app requests is in the latest encoding format.

Precautions

  • Do not use push tokens to trace and mark users.
  • Do not let your app verify the push token length because it is variable.
  • Do not request tokens frequently. An app that is not running in the background requests a token each time when the app is launched. It is prohibited for an app running in the background to request tokens frequently. If tokens must be requested periodically, it is recommended that the request period be greater than one day.
  • Use the getToken method to obtain a push token only after you enable Push Kit in AppGallery Connect.
  • Declare both the getToken and onNewToken methods in the code to ensure that the push token can be returned.

Procedure

It is recommended that the getToken method be called in the onCreate method of the first Activity class after app startup.

  1. Call the getToken method to obtain a push token.
    NOTE
    • You are advised not to obtain a push token in a subprocess.
    • If the getToken method is called in multiple scenarios, ensure that the value of appId is the same for all scenarios.
    • You need to add exception capture code surrounded with the getToken method. After a push token is obtained by using the getToken method, check whether the obtained token is set to null.
    • For details about the HmsInstanceId class and its methods, please refer to HmsInstanceId.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. private void getToken() {
    2. // Create a thread.
    3. new Thread() {
    4. @Override
    5. public void run() {
    6. try {
    7. // Obtain the app ID from the agconnect-services.json file.
    8. String appId = "your APP_ID";
    9. // Set tokenScope to HCM.
    10. String tokenScope = "HCM";
    11. String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, tokenScope);
    12. Log.i(TAG, "get token: " + token);
    13. // Check whether the token is null.
    14. if(!TextUtils.isEmpty(token)) {
    15. sendRegTokenToServer(token);
    16. }
    17. } catch (ApiException e) {
    18. Log.e(TAG, "get token failed, " + e);
    19. }
    20. }
    21. }.start();
    22. }
    23. private void sendRegTokenToServer(String token) {
    24. Log.i(TAG, "sending token to server. token:" + token);
    25. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. private fun getToken() {
    2. // Create a thread.
    3. object : Thread() {
    4. override fun run() {
    5. try {
    6. // Obtain the app ID from the agconnect-services.json file.
    7. val appId = "your APP_ID"
    8. // Set tokenScope to HCM.
    9. val tokenScope = "HCM"
    10. val token = HmsInstanceId.getInstance(this@MainActivity).getToken(appId, tokenScope)
    11. Log.i(TAG, "get token:$token")
    12. // Check whether the token is null.
    13. if (!TextUtils.isEmpty(token)) {
    14. sendRegTokenToServer(token)
    15. }
    16. } catch (e: ApiException) {
    17. Log.e(TAG, "get token failed, $e")
    18. }
    19. }
    20. }.start()
    21. }
    22. private fun sendRegTokenToServer(token: String) {
    23. Log.i(TAG, "sending token to server. token:$token")
    24. }
  2. Override the onNewToken method in your service (extended HmsMessageService). When the push token changes, the new push token can be returned through the onNewToken method.
    NOTE
    • After a push token is obtained, check whether the token is set to null.
    • If the integrated Push SDK version is earlier than 5.0.4.302, update it to the latest one.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. @Override
    2. public void onNewToken(String token, Bundle bundle) {
    3. // Obtain a push token.
    4. Log.i(TAG, "have received refresh token " + token);
    5. // Check whether the token is null.
    6. if (!TextUtils.isEmpty(token)) {
    7. refreshedTokenToServer(token);
    8. }
    9. }
    10. private void refreshedTokenToServer(String token) {
    11. Log.i(TAG, "sending token to server. token:" + token);
    12. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. override fun onNewToken(token: String, bundle: Bundle) {
    2. // Obtain a push token.
    3. Log.i(TAG, "have received refresh token:$token")
    4. // Check whether the token is null.
    5. if (token.isNotEmpty()) {
    6. refreshedTokenToServer(token)
    7. }
    8. }
    9. private fun refreshedTokenToServer(token: String) {
    10. Log.i(TAG, "sending token to server. token:$token")
    11. }

Deleting a Push Token

Scenario Description

After a user rejects the user agreement and privacy statement of your app, you can call the deleteToken method to delete the corresponding push token from the Push Kit server. After doing so, your app on the user device will no longer receive push messages from your app server.

You are advised not to call the deleteToken method to delete the push token. Instead, it is recommended that you invalidate push tokens for users who reject your app's user agreement and privacy statement, and control your app server not to send messages to your app with invalid push tokens. This can reduce the frequency for your app server to request the Push Kit server.

NOTE
  • Do not delete push tokens frequently.
  • To delete a push token, ensure that the HMS Core (APK) version is 3.0.0 or later.
  • If you do not want your app to receive notification messages, you can call the turnOffPush method to disable the function of displaying notification messages.
  • The user agreement and privacy statement of your app must include and comply with the HUAWEI Push Service Agreement and SDK Privacy and Security Statement.

Procedure

The following shows the sample code in different programming languages for deleting a push token:

Java
Kotlin
Collapse
Word wrap
Dark theme
Copy code
  1. private void deleteToken() {
  2. // Create a thread.
  3. new Thread() {
  4. @Override
  5. public void run() {
  6. try {
  7. // Obtain the app ID from the agconnect-services.json file.
  8. String appId = "your APP_ID";
  9. // Set tokenScope to HCM.
  10. String tokenScope = "HCM";
  11. // Delete the token.
  12. HmsInstanceId.getInstance(context).deleteToken(appId, tokenScope);
  13. Log.i(TAG, "token deleted successfully");
  14. } catch (ApiException e) {
  15. Log.e(TAG, "delete token failed." + e);
  16. }
  17. }
  18. }.start();
  19. }
Collapse
Word wrap
Dark theme
Copy code
  1. private fun deleteToken() {
  2. // Create a thread.
  3. object : Thread() {
  4. override fun run() {
  5. try {
  6. // Obtain the app ID from the agconnect-services.json file.
  7. val appId = "your APP_ID"
  8. // Set tokenScope to HCM.
  9. val tokenScope = "HCM"
  10. // Delete the token.
  11. HmsInstanceId.getInstance(this@MainActivity).deleteToken(appId, tokenScope)
  12. Log.i(TAG, "token deleted successfully")
  13. } catch (e: ApiException) {
  14. Log.e(TAG, "delete token failed, $e")
  15. }
  16. }
  17. }.start()
  18. }

Automatic Initialization

Push SDK 4.0 or later provides the capabilities of automatically generating AAIDs and automatically obtaining push tokens. With the capabilities enabled, you do not need to explicitly call the getToken method to obtain a push token. The token is returned through onNewToken. You can implement automatic initialization in either of the following methods:

  • Method 1:
    Add the meta-data element to application in the AndroidManifest.xml file. The following is the sample code, in which the value of name is always push_kit_auto_init_enabled and value indicates whether to enable automatic initialization. The options are true (yes) and false (no).
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. <manifest ...>
    2. ...
    3. <application ...>
    4. <meta-data
    5. android:name="push_kit_auto_init_enabled"
    6. android:value="true"/>
    7. ...
    8. </application>
    9. ...
    10. </manifest>
  • Method 2 (recommended)

    Explicitly call the setAutoInitEnabled method in the MainActivity class. In the method, the enable parameter indicates whether to enable automatic initialization. The options are true (yes) and false (no). The parameter value will be saved in a file in the shared_prefs directory on your app.

    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. private void setAutoInitEnabled(final boolean isEnable) {
    2. if(isEnable){
    3. // Enable automatic initialization.
    4. HmsMessaging.getInstance(this).setAutoInitEnabled(true);
    5. } else {
    6. // Disable automatic initialization.
    7. HmsMessaging.getInstance(this).setAutoInitEnabled(false);
    8. }
    9. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. private fun setAutoInitEnabled(isEnable: Boolean) {
    2. if (isEnable) {
    3. // Enable automatic initialization.
    4. HmsMessaging.getInstance(this).isAutoInitEnabled = true
    5. } else {
    6. // Disable automatic initialization.
    7. HmsMessaging.getInstance(this).isAutoInitEnabled = false
    8. }
    9. }
NOTICE
  • If your app provides the usage agreement and privacy statement and requires users to agree to them, use method 2 for automatic initialization. If you choose method 1, an AAID is automatically generated and a token is automatically obtained when your app is launched. That is, automatic initialization is triggered before the users agree to the usage agreement and privacy statement, which does not meet the requirements for protecting personal data.
  • After obtaining the users' consent, call the setAutoInitEnabled method to enable automatic initialization.
  • If the setting of push_kit_auto_init_enabled is stored in the file in the shared_prefs directory of your app on the device, the Push SDK will directly read the setting from the file and determine whether automatic initialization is enabled. If the setting is not stored there, the Push SDK will read the setting in meta-data and determine whether automatic initialization is enabled.
Search in Guides
Enter a keyword.