Overview

HUAWEI Push Kit is a messaging service provided by Huawei for developers. It establishes a messaging channel from the cloud to devices. By integrating HUAWEI Push Kit, developers can send messages to apps on users' devices in real time. This helps developers maintain closer ties with users and increases user awareness and engagement. The following figure shows the process of sending messages from the cloud to a device.

  1. App servers call APIs to send messages to HUAWEI Push Kit.
  2. HUAWEI Push Kit forwards the messages to devices with corresponding apps installed.

You need to perform the following operations:

What You Will Create

In this codelab, you will use the demo project that has been created for you to call HUAWEI Push Kit APIs. Through the demo project, you will:

What You Will Learn

Hardware Requirements

Software Requirements

To integrate HUAWEI HMS Core services, you must complete the following preparations:

For details, please refer to Preparations for Integrating HUAWEI HMS Core.

Enabling HUAWEI Push Kit Service

For details, please refer to Enabling Services.

Setting the Data Storage Location

To use HUAWEI Push Kit, you must set the data storage location. For details, please refer to Setting Data Storage Location. If the data storage location is not set, the following functions will be unavailable: topic-based messaging, messaging through the WebPush agent, and messaging to iOS apps.

Setting HUAWEI Push Kit Parameters

For details, please refer to Configuring Push Service Parameters.

Adding the AppGallery Connect Configuration File of Your App

Download the agconnect-services.json file.

Move the downloaded agconnect-services.json file to the app directory of your Android Studio project.

Adding Build Dependencies

Open the build.gradle file in the app directory.

Add all the following build dependencies to dependencies:

dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' // Add the following line implementation 'com.huawei.hms:push:5.0.0.300' }

Configuring Obfuscation Scripts

  1. Open the obfuscation configuration file proguard-rules.pro of your Android Studio project.
  2. Add configurations to exclude HUAWEI Push Kit SDK from obfuscation.
    -ignorewarnings -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keepattributes SourceFile,LineNumberTable -keep class com.hianalytics.android.**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;}
  3. If you have used AndResGuard, add the AndResGuard allowlist to the obfuscation configuration file.
    "R.string.agc*", "R.string.hms*", "R.string.connect_server_fail_prompt_toast", "R.string.getting_message_fail_prompt_toast", "R.string.no_available_network_prompt_toast", "R.string.third_app_*", "R.string.upsdk_*", "R.layout.hms*", "R.layout.upsdk_*", "R.drawable.upsdk*", "R.color.upsdk*", "R.dimen.upsdk*", "R.style.upsdk*"

Click Sync Now to synchronize the project.

If "synced successfully" is displayed, the synchronization is successful.

Declare Service under application in the AndroidManifest.xml file so that devices can receive the push token and messages sent by the HUAWEI Push Kit server. Define the MyPushService class by extending the HmsMessageService class.

<service android:name=".MyPushService" android:exported="false"> <intent-filter> <action android:name="com.huawei.push.action.MESSAGING_EVENT" /> </intent-filter> </service>

The following figure shows the overall project code and resource structure.

Creating a Project

Create a project in Android Studio. For details, please refer to the Creating an Android Studio Project.

Creating a Widget

Deploy TextView in MainActivity to display the token.

In MainActivity, code the method for updating token in TextView.

public class MainActivity extends AppCompatActivity { private TextView tvToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvToken = findViewById(R.id.tv_log); MyReceiver receiver = new MyReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction("com.huawei.codelabpush.ON_NEW_TOKEN"); MainActivity.this.registerReceiver(receiver,filter); } public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("com.huawei.codelabpush.ON_NEW_TOKEN".equals(intent.getAction())) { String token = intent.getStringExtra("token"); tvToken.setText(token); } } } }

Completing Service Code

Applying for a Token

Declare <meta-data> under application in the AndroidManifest.xml file.

<application <meta-data android:name="push_kit_auto_init_enabled" android:value="true" /> </application>

Receiving a Token

A token is received by the onNewToken method in the MyPushService class.

MyPushService.java

public class MyPushService extends HmsMessageService { private static final String TAG = "PushDemoLog"; @Override public void onNewToken(String token) { super.onNewToken(token); Log.i(TAG, "receive token:" + token); sendTokenToDisplay(token); } private void sendTokenToDisplay(String token) { Intent intent = new Intent("com.huawei.push.codelab.ON_NEW_TOKEN"); intent.putExtra("token", token); sendBroadcast(intent); } }

The MyPushService class extends the HmsMessageService class to override the onNewToken method in the HmsMessageService class to receive token.

Other Functions

For details about other functions of HUAWEI Push Kit, such as subscribing to a topic, and sample code, please refer to the HUAWEI Push Kit Development Guide.

Building, Loading, and Debugging the App

Connect your Huawei phone to a computer.

Method 1:

Click to start compilation and building, and install the APK to your Huawei phone.

Method 2:

1.Use Android Studio to package the APK.

2.Use the ADB tool to install the APK to your Huawei phone for debugging.

adb install D:\WorkSpace\CodeLab\push_demo1\app\release\app-release.apk

After running the demo, ensure that your Huawei phone is connected to the network. Click getToken to obtain the token. The token is recorded in the log. Search for PushDemoLog: to view all logs of the demo.
1) If your Huawei phone runs EMUI 10.0 or later, the getToken method directly returns the token ADHpIj5s3j6jxaYJUW7miEx6vY5TtUgb8_v1IXIbvf5g4e0Nb4ztnJ7******* in the return value.

2) If your Huawei phone runs EMUI earlier than 10.0 or a cached token request is sent again, the onNewToken method is called to return the token AFcSAHhhnxdrMCYBxth2QOG9IgY2VydAM61DTThqNux3KBC_hgzQQT*******.

On the HUAWEI Push Kit console in AppGallery Connect, you can edit messages and send them to devices that have obtained tokens from the HUAWEI Push Kit server. For details, please refer to Sending Messages from the HUAWEI Push Kit Console. Before sending notification messages, search for the app by app name. In this example, the APK name of the app is com.huawei.codelabpush.

After successful message sending, you will receive the notification messages on your phone.

Well done. You have successfully completed this codelab and learned how to:

For more information, please click the following link:

Related documents

You can click the button below to download the source code.

Download source code

Code copied