目录

Obtaining and Deleting a Push Token

Obtaining a Push Token

[h2]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.

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.

[h2]Precautions

[h2]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.
    • 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
    private void getToken() {
        // Create a thread.
        new Thread() {
            @Override
            public void run() {
                try {
                    // Obtain the app ID from the agconnect-services.json file.
                    String appId = "your APP_ID";
    
                    // Set tokenScope to HCM.
                    String tokenScope = "HCM";
                    String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, tokenScope);
                    Log.i(TAG, "get token: " + token);
                    
                    // Check whether the token is null.
                    if(!TextUtils.isEmpty(token)) {
                        sendRegTokenToServer(token);
                    }
                } catch (ApiException e) {
                    Log.e(TAG, "get token failed, " + e);
                }
            }
        }.start();
    }
    private void sendRegTokenToServer(String token) {
        Log.i(TAG, "sending token to server. token:" + token);
    }
    Kotlin
    private fun getToken() {   
        // Create a thread.
        object : Thread() {
            override fun run() {
                try {
                    // Obtain the app ID from the agconnect-services.json file.
                    val appId = "your APP_ID"
                    
                    // Set tokenScope to HCM.
                    val tokenScope = "HCM"
                    val token = HmsInstanceId.getInstance(this@MainActivity).getToken(appId, tokenScope)
                    Log.i(TAG, "get token:$token")
                    
                    // Check whether the token is null.
                    if (!TextUtils.isEmpty(token)) { 
                        sendRegTokenToServer(token)
                    }                
                } catch (e: ApiException) { 
                    Log.e(TAG, "get token failed, $e")
                }
            }
        }.start()
    }
    private fun sendRegTokenToServer(token: String) { 
        Log.i(TAG, "sending token to server. token:$token")
    }
  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.
    • 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
    @Override
    public void onNewToken(String token, Bundle bundle) {         
        // Obtain a push token.
        Log.i(TAG, "have received refresh token " + token);
        
        // Check whether the token is null.
        if (!TextUtils.isEmpty(token)) {
            refreshedTokenToServer(token);
        }
    }
    
    private void refreshedTokenToServer(String token) {
        Log.i(TAG, "sending token to server. token:" + token);
    }
    Kotlin
    override fun onNewToken(token: String, bundle: Bundle) {    
        // Obtain a push token.
        Log.i(TAG, "have received refresh token:$token")
        
        // Check whether the token is null.
        if (token.isNotEmpty()) { 
            refreshedTokenToServer(token)    
        }
    }
    
    private fun refreshedTokenToServer(token: String) { 
        Log.i(TAG, "sending token to server. token:$token")
    }

Deleting a Push Token

[h2]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.

  • 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.

[h2]Procedure

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

Java
private void deleteToken() {
    // Create a thread.
    new Thread() {
        @Override
        public void run() {
            try {
                // Obtain the app ID from the agconnect-services.json file.
                String appId = "your APP_ID";
                
                // Set tokenScope to HCM.
                String tokenScope = "HCM";

                // Delete the token.
                HmsInstanceId.getInstance(context).deleteToken(appId, tokenScope);
                Log.i(TAG, "token deleted successfully");
            } catch (ApiException e) {
                Log.e(TAG, "delete token failed." + e);
            }
        }
    }.start();
}
Kotlin
private fun deleteToken() {   
    // Create a thread.
    object : Thread() {
        override fun run() {
            try {
                // Obtain the app ID from the agconnect-services.json file.
                val appId = "your APP_ID"
                
                // Set tokenScope to HCM.
                val tokenScope = "HCM"

                 // Delete the token.
                HmsInstanceId.getInstance(this@MainActivity).deleteToken(appId, tokenScope)
                Log.i(TAG, "token deleted successfully")
            } catch (e: ApiException) { 
                Log.e(TAG, "delete token failed, $e")
            }
        }
    }.start()
}

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:

  • 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.