How Huawei’s Push Kit works

Hello, Habr! In May last year, left without Google services and APIs, we thoroughly set to work on our platform Huawei Mobile Services… This is our long-standing project, to which we returned after the imposition of US sanctions. The problem of “cut off” services gradually faded away. We have added missing components: an email client, our own maps and other services, and HMS Core – a set of APIs, SDKs and other services for developing and improving applications. This set includes the Push Kit – a cloud-based notification service – and more. Under the cut, we will tell you how this tool works, how it stands out and how it can be used.

The main function of the Push Kit (we’ll talk about the rest later) is to deliver notifications from applications to the user’s device. This process is organized like this:

  • the application server connects to the Push Kit API and uploads encrypted messages there;

  • From the Push Kit cloud, messages are forwarded to the device with the target application.

Besides, the Push Kit has many interesting and useful features:

  • Targeting mailings by subject lines and other criteria, including using the Huawei Analytics Kit;

  • Sending push messages based on scripts to one or several users at the same time, sending out according to a schedule;

  • Sending push messages through the console in the AppGallery Connect interface.

  • Access to the Push Kit server via HTTPS;

  • Sending push messages to users using different profiles on the same Android device;

  • Sending push messages to Android / iOS devices and web applications;

  • Automatic selection of the language of the push message depending on the system language of the recipient’s device;

  • Caching and resending – in case the push message is not delivered due to the lack of a network.

What and how can be sent via Push Kit

With the Push Kit, you can not only deliver notifications, but also transfer data directly to the app. In this case, a “message” arrives at the user device, which activates a specific action in the destination program. The function can be useful, for example, for social networks, when you receive a request to add as a friend or incoming calls via VoIP. In addition, with its help, you can upload messages to instant messengers so that they are already inside when you start the program.

Still, the main task is to deliver push notifications, the appearance of which is configured through the Push Kit interface. It can be plain text, text with a large or small picture, with an application icon, etc. You can change the size of elements and their position, select the type of sound signal, and also program scripts – actions that are performed when the user opens a notification.

If a group of notifications from one application in the status bar is minimized, the first two pushes will be shown in it by default – their number can be expanded to eight. Such a group can contain up to 24 push notifications in EMUI 10 and up to 49 in EMUI 9. If there are more messages, the counter of the remaining notifications will be visible and the next one will appear only after one of the displayed push notifications has been deleted.

The packet name sent by the Push Kit can be up to 128 bytes, and the maximum message size is 4KB.

If the target device has no network problems, push notifications should be delivered in no longer than 1 second. If the recipient’s device is offline, Push Kit caches the message and sends it after the device goes online.

Features of Push Kit

Push Kit notifications arrive quickly and reduce device power consumption. Operating systems of most mobile devices automatically close applications that have been inactive for a long time. But for the program to show its push notifications, it often needs to work – at least in the background. So the system has to restart the software it needs to display the push on the screen.

Push Kit allows you not to do this: messages go to its notification center (NC), bypassing targeted applications. A special component called Push Service is responsible for this. As a result, the program starts only when it is provided by the script, for example, after clicking on the notification.

Hence the high delivery speed: thanks to the Push Service, the user can read the message almost immediately after it arrives on the phone.

Push Kit provides system-level channelcapable of simultaneously sending tens of millions of messages per second and tens of billions per day. Moreover, 99% of push notifications are delivered to users within 10 minutes, even if the application is not running. Basically, notifications only fail if the recipient’s device is turned off or offline.

Push Service is installed on all mobile devices with EMUI, so they display notifications in a unified form

The Notification Center service is available on some Huawei devices with EMUI 4 and on all devices starting from EMUI 5. But this function is not available on third-party gadgets, but if you install HMS Core on them, these phones will also learn to receive notifications sent via Huawei Push Kit. Alas, due to system restrictions, the delivery speed for phones of other brands may decrease.

Push kit supports major cross-platform development environments mobile apps including React Native, Cordova, Xamarin and Flutter. To develop an app in the same language that will run on both iOS and Android, you only need to integrate the appropriate SDK plugin.

After receiving messages via Push Kit, user devices inform your server about it, helping track the progress of the mailing in real time… Thanks to this, you can be aware of the status of each notification and be able to quickly respond to unsuccessful delivery. For example, send an SMS to a person who does not receive push notifications.

Push Kit automatically shows push notificationsthat is installed on the user’s device. The coverage of Push Kit is over 200 countries and regions, so this feature will be very useful.

Under the hood Push Kit: some practice

To use the service, you need to register a developer account on the site Huawei Developers… In addition, you will need:

  • Windows computer with Java JDK 1.8, Android Studio and Android SDK installed;

  • Huawei smartphone with a USB cable and installed HMS Core at least version 4.

The diagram shows the process of developing an Android application. iOS and web applications are supported in beta mode.

First thing:

  • create an application in AppGallery Connect and a project in Android Studio;

  • generating a SHA-256 cryptographic key;

  • save the application configuration file;

  • connect the AppGallery Connect module to the application;

  • add the Maven repository to the file build.gradle.

You can read more about these steps. here, however, in English.

An important point: To use Push Kit for web apps, you need to set it up via the Android app. In addition, there are Quick Apps, a no-install application that can be used on more than 12 major mobile phone manufacturers in China. They are all available in the AppGallery and support the Push Kit.

To use Push Kit, indicate a place to store your project data. If you do not set it, targeting by message subject, distribution via the WebPush agent, and work with iOS will not be available.

If the storage location is different from the location of your server or the user’s region, the delivery time of push notifications will increase.

To reduce latency, it makes sense to store data close to users. For example, if you are developing an application in Russia for residents from the European Union, the best place for the server would be Germany.

HMS Core SDK Integration

Let’s add your application configuration file to AppGallery Connect.

  1. In AppGallery Connect, click My project

  2. We find and select the application into which we want to integrate the HMS Core SDK.

  3. Go to Project Setting → General information… AT App information upload the file agconnect-services.json

  4. Copy the file agconnect-services.json to the application root of our Android Studio project.

Let’s add assembly links. To do this, open the file build.gradle in the application directory.

We register in the section 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'
}

5.0.0.300 we will replace it with the latest version of HMS Core Push SDK.

Push Sync Now, to sync your build.gradle file.

If displayed synced successfully, everything went well.

Configuring the Manifest File

To enable devices to receive the push token and messages sent by the Push Kit server, you need to modify the file AndroidManifest.xml Defining a class MyPushService, it inherits from the class HmsMessageService

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

In this code example, you only need to change MyPushService at android: name = “. MyPushService” to the name of the class inherited from the class HmsMessageService… We save the rest.

Setting up encryption scripts

Opening the obfuscation configuration file proguard-rules.pro Android Studio project. We add parameters that exclude the HMS Core SDK from this process.

-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.**{*;}

If we use AndResGuard, it must be added to the list of permissions in 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*"

We develop a demo

Below is the general project code and resource structure.

We open our project in Android Studio, create a widget and expand the TextView into MainActivity, to display the token. Ibid, in MainActivity, we program the method to update the token in the 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);
            }
        }
    }
}

To apply for a token, we announce in file AndroidManifest.xml

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

Name and value at meta-data copy without changes. The Push SDK will apply for a token when the app launches.

The token is obtained by the method onNewToken in thMyPushService *ce 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);
    }
}

Class MyPushService inherited from HmsMessageService… It, in turn, overrides the method for confirming the online status of a device – onNewToken

Building, loading and debugging the application

We connect the Huawei phone to the computer.

Method 1. Push Play (green triangle) to start compiling and building. Install the APK on your phone.

Method 2. We use Android Studio to package the APK.

Then use the ADB tool to install the APK on the phone for debugging.

adb install D:WorkSpaceCodeLabpushdemo1appreleaseapp-release.apk

After starting the demo, make sure that the phone is connected to the network. Method onNewToken called to return a token AFcSAHhhnxdrMCYBxth2QOG9IgY2VydAM61DTThqNux3KBC_hgzQQT *******

The token is written to the demo log. It can be viewed by finding PushDemoLog

Sending push notifications

In the Push Kit interface in AppGallery Connect, you can edit messages and send them to devices connected to the network. Before sending notifications, we find the application by name. In this example, the APK name is com.huawei.codelabpush. More details can be read here

If everything went well, we will see a notification on the phone screen.

Commercial opportunities of Push Kit

Almost all Russian cases known to us are related to banking institutions.

The first domestic and second in the world company to integrate our Push Kit became mfms °: their solutions for the delivery of push notifications are used by VTB, Alfa-Bank, Sberbank and other financial institutions in Russia.

For example, at VTB, customers are notified of money transactions in real time by push notifications. Such notifications are much cheaper than SMS, and the implementation costs are minimal: with the SDK provided by mfms °, you do not need to integrate APNs, FCM and Huawei Push Kit from scratch.

Push notifications are used not only for distribution. Based on the Push Kit, mfms ° has developed a feature that allows bank customers to receive notifications with confirmation of money transactions. Such messages are sent via the SDK and replace SMS with payment codes. Moreover, mfms ° have learned how to turn these push notifications into beautiful notifications in Russian with a branded name, logo and category of the store in which the user made a payment.

What other applications can be found for push notifications and how to get more benefit from the Push Kit – the questions are not so difficult, but extremely interesting for us. Let’s discuss them in the comments: we are waiting for your ideas, use cases for the platform, or, perhaps, predictions about the future of push notifications.

Similar Posts

Leave a Reply