Using Push Kit With Kotlin, Java And Developer Console

Berk Özyurt
Huawei Developers
Published in
7 min readJun 5, 2020

Hello everyone.

This article about how to send notification on android device and developer console with Huawei Push Kit. Firstly I would like to give some detail about Push Kit.

What Is Push Kit?

Push Kit is a messaging service provided by Huawei for developers. Push Kit 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. Push Kit helps developers rapidly reach the target audience. Push notification can be sent to everyone or to a specific person individually. For send notification , user’s token is required. You can send messages to a device group or specific user. Push Kit has two different notification type. Text only style (Shows longer text messages) and big picture style (Shows large text and image messages)

Supported Devices

•Huawei Android devices that have HMS Core (APK) installed

•Non-Huawei Android devices that have no HMS Core (APK) installed

  • IOS devices

Development Preparations

1. Register as a developer

Firstly, you have to register as developer on AppGallery Connect and create an app.

You can find the guide of registering as a developer here : https://developer.huawei.com/consumer/en/doc/10104

2. Create an app

You can find the guide of creating app here :

https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createproject

3. Generate a Signing Certificate Fingerprint

Firstly, create a new project on Android Studio. Secondly, click gradle tab on the right of the screen.

Finally, click Task > android > signingReport. And you will see on console your projects SHA-256 key.

Copy this fingerprint key and go AppGallery Console > My Apps > select your app > Project Settings and paste “SHA-256 certificate fingerprint” area. Don’t forget click the tick on the right.

4.Enabling Push Kit

In HUAWEI Developer AppGallery Connect, go to Develop > Overview > Manage APIs and enable Push Kit on this page.

Select the “Push Kit” from the menu on the left and activate the service by clicking the Enable Now button.

5.Download agconnect-service.json file

The service file is downloaded by clicking the agconnect-services.json button on the Project Settings page. Move the downloaded agconnect-services.json file to the app directory of your Android Studio project.

6.Adding Dependencies

  • Open the build.gradle file in the root directory of your Android Studio project.
  • Go to buildscript > repositories and allprojects > repositories, and configure the Maven repository address for the HMS SDK.
buildscript {

repositories {
maven { url 'http://developer.huawei.com/repo/' }
google()
jcenter()

}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
}
}

allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
}
  • Add dependencies in build.gradle file in app directory.
dependencies {   implementation 'com.huawei.hms:push:4.0.3.301'}
  • Add the AppGallery Connect plug-in dependency to the file header.
apply plugin: 'com.huawei.agconnect'
  • Configure the signature in android. Copy the signature file generated in Generating a Signing Certificate Fingerprint to the app directory of your project and configure the signature in the build.gradle file.
android {  signingConfigs {    release {      storeFile file("**.**") //Signing certificate.      storePassword "******" //Keystore password.      keyAlias "******" //Alias.      keyPassword "******" //Key password.      v2SigningEnabled true    }  }  buildTypes {    release {      minifyEnabled false      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'      signingConfig signingConfigs.release    }    debug {      signingConfig signingConfigs.release}    }  }}

Develop Project With Kotlin

1. PushService Class

PushService class is a background service for Push Kit. Thanks to this class, device receive a notification, and create new token. PushService class should extends HmsMessageService. Override onNewToken and onMessageRecieved methods.

Add PushService.class to AndroidManifest.xml as a service. Thanks to this service, device will receive a notification.

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

2. Add Retrofit Library and Create Model Class

Add Retrofit library to build.gradle

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation(
[group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1'],
)
  • Create AccessTokenModel class

Some parameters are required to send notifications from the device.
One of them is AccessToken. A post request must be made to receive AccessToken. A second way is to use AccesToken, which is produced using the Account Kit or Auth Service, as a parameter. In this article, an AccessToken will be received by making a post request with Retrofit. If you used Account Kit or Auth Service, please go second step of that article(Develop with Java)

AccessTokenModel class for response of the post request. This class is for the response of the Post request. It will be used to get the AccessToken values in the response.

data class AccessTokenModel (

var access_token : String,
var expires_in : Int,

var token_type : String

)

3. Create AccessTokenClient Class

4. Create AccessTokenInterface Class

interface AccessTokenInterface {

@FormUrlEncoded
@Headers("Content-Type:application/x-www-form-urlencoded; charset=UTF-8")
@POST("oauth2/v3/token")
fun createAccessToken(
@Field("grant_type") grant_type : String,
@Field("client_secret") client_secret : String,
@Field("client_id") client_id : String) : Call<AccessTokenModel>

}
  • This class contains the parameters for make post request.
  • Post request should make base url + oauth/v3/token address.
  • Header parameters:
Content-Type : application/x-www-form-urlencodedPost : oauth/v3/token
  • Body parameters:
grant_type : client_credentialsclient_secret : Your_App_Secret _Keyclient_id : Your_App_ID

5. Create NotificationClient Class

5. Create NotificationInterface Class

  • This class contains the parameters for make post request.
  • Post request should make base url + v1/App_ID/messages:send address.
  • Header parameters:
Content-Type : application/x-www-form-urlencodedPost : v1/App_ID/messages:send
  • Body parameters:

Create NotificationMessageBody model class This classs should include tittle, body, tokens.

And create a notification client :

@Headers("Content-Type:application/json; charset=UTF-8")
@POST("v1/APP_ID/messages:send")
fun createNotification(
@Header("Authorization") authorization: String?,
@Body notifMessageBody: NotificationMessageBody) : Call<NotificationMessageModel>
}

6. Create new activity for send notification

  • This activity should include get token method, post acces token method and post notification method.
  • Firstly token should get. Secondly Access Token should get. And finally notification will send.

Send Notification By Push Kit Console

1.Login developer console.

2.Click “Huawei AppGallery Connect”

3.Go “My Apps” and select your app.

4.Click “Delevop” tab.

5.Select “Push Kit” on left menu.

6.Click “Add Notification”

7.Enter content parameters here.

8.Only you can see name area.

9.Enter header, tittle and body parameters.

10.Select push scope on “Push Scope” area.

11.You can send specific device or all of the users.

12.Determine when to send the notification on “Push Time” area.

13.You can send now, or schedule a specific time.

14.And finally, click submit button for send notification.

Develop Project With Java

1. PushService Class

PushService class is a background service for Push Kit. Thanks to this class, device receive a notification, and create new token. PushService class should extends HmsMessageService. Override onNewToken and onMessageRecieved methods.

Add PushService.class to AndroidManifest.xml as a service. Thanks to this service, device will receive a notification.

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

2. Add Retrofit Library and Auth Service

  • Add Retrofit libraries to build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation(
[group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'],
[group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1'],
)
implementation 'com.huawei.hms:hwid:4.0.1.300'
  • Create login/authorization class. In this class you have to use account kit or auth service for get access token. You can find document of account kit in this link.

3. Create NotificationClient Class

4. Create NotificationInterface

@Headers("Content-Type:application/json; charset=UTF-8")
@POST("v1/APP_ID/messages:send")
Call<DBResponse<EmptyResponse>> createNotification(
@Header("Authorization") String authorization,
@Body NotificationMessageBody notificationBody

);
  • This class contains the parameters for make post request.
  • Post request should make base url + v1/App_ID/messages:send address.
  • Header parameters:
Content-Type : application/x-www-form-urlencodedPost : v1/App_ID/messages:send
  • Body parameters:

Create NotificationMessageBody class

This classs should include tittle, body, tokens.

5. Create new activity for send notification

  • This activity should include get token method and post notification method.
  • Firstly token should get. And finally notification will send. Access Token was created on login page.

Result

In this article, I wrote about sending notifications from app both the Kotlin and the Java. I also wrote sending a notification with the Developer Console.

I hope that article include useful information for everyone. Thank you for reading.

--

--