Integrate AGC UI in 15 Minutes - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum​
AGC UI is a one stop solution where multiple third party providers can be integrated using Huawei AGC Auth Service for authentication. AGC UI provides our user to login by any third party providers and we can validate their identity without any requirement to implement our own backend servers. AGC UI has many features which we can utilize:
1) Has similar functionality as Firebase UI
2) Provides user token validation at server side
3) User can login in and link multiple third party providers in an application.
4) Has a default theme, but can be customize easily according to our need.
5) It is an open source library
Need of AGC UI
1) Firebase UI will not work on HMS devices.
2) Firebase UI provides multiple providers sign in at a single place.
3) Required single UUID for multiple providers.
4) Developer has no longer require to focus on UI part, it saves lot of integration time.
How it works?
1) Client app request for the UI to AGC UI library.
2) Based on the selection of the provider's, UI will be shown to client App.
3) User select specific provider for Authentication.
4) AGC UI will request the selected provider authentication page.
5) Show the authorization page to user in browser.
6) User enters their credentials.
7) AGC Server authenticate the user and returns the SignInResult to the client app.
Instead of writing boiler plate codes for third party providers which we need in our application for our users to authenticate using Huawei Auth Service, AGC UI allows us to authenticate users through a number of different third party providers avoiding boiler plate codes, providing us with both variety and flexibility when it comes to authentication within our applications. In this article we will see two ways of integrating AGC UI in our application:
a) Default theme
b) Customization theme
Demo
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things need to be done
1) Create a project in android studio.
2) Get the SHA Key. For getting the SHA key, refer this article.
3) Create an app in the Huawei AppGallery connect.
4) Enable Auth Service setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below class path dependencies in project build.gradle file:
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
10) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: ‘com.huawei.agconnect’
11) Enter the below permission in android manifest file
Code:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
12) Now Sync the gradle.
Common steps required
As I mentioned earlier there are two ways we can integrate AGC UI in our application but both the ways required to follow a common steps to work with AGC UI library:
Enabling Huawei account, email address and mobile number
1) Navigate to AGC UI Github repository
https://github.com/Huawei-DTSE-India-Delhi-NCR/AGC-UI-Auth
2) Select AGC-UI-AUTH-MODULE as shown below:
3) Download the code as shown below:
4) Open the your android project and make the following changes in the app build.gradle file:
Code:
minSdkVersion 17 dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
5) Import the downloaded AGC-UI-AUTH-MODULE library as dependencies using project structure settings in your project and after importing the module the app build.gradle file should look like this:
Code:
implementation project(path: ':agcbase')
implementation project(path: ':agccommon')
implementation project(path: ':agcfacebook')
implementation project(path: ':agcphone')
implementation project(path: ':agcemail')
implementation project(path: ':agcgoogle')
implementation project(path: ':agchuweiid')
6) Navigate to AGC console and select your project.
7) Select Auth Service under your project Build
8) Enable mobile number, email address Authentication mode.
9) Enable Huawei account and provide your APP ID and APP SECRET of your project as shown below:
Enabling Facebook
1) Navigate to Facebook developer console. If you have not registered yourself as a developer yet, then Facebook will ask you to register as a developer.
2) Create new app and select android as platform.
3) Provide your project package name and Key Hash. For key hash put the below code in onCreate method of your project and run the project:
Code:
private void getFbHashKey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.huawei.hmsui",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
4) After creating the app get the App ID and App Secret of Facebook.
5) Enable Facebook authentication mode and provide the App ID and App Secret in Auth Service.
6) Add following facebook configuration into your application string.xml file
Code:
<string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
<string name="fb_login_protocol_scheme">YOUR_FACEBOOK_APP_SECRET </string>
Enabling Twitter
1) Navigate to Twitter developer console. If you have not registered yourself as a developer yet, then Twitter will ask you to register as a developer.
2) Create a new app.
3) Get the API key and API key Secret.
4) Enable Twitter authentication mode in Auth Service and provide the API key and API secret key shown below:
e) In order to avoid “Failed to get request token” error we need to provide twittersdk:// as Callback URLs, website URL, Terms and Service and Privacy Policy in twitter authentication settings section.
f) Add following twitter configuration into your application string.xml file.
Code:
<string name="twitter_api_key">YOUR_TWITTER_API_KEY</string>
<string name="twitter_api_secret">YOUR_TWITTER_API_KEY_SECRET </string>
Enabling Google
1) Go to Google Developer Console. If you have not registered yourself as a developer yet, then Twitter will ask you to register as a developer.
2) Create your project. Provide your package name and SHA1 key there and get the Client ID and Client Secret.
3) Enable Google authentication mode in Auth Service and provide the Client ID and Client Secret as shown below:
4) Add following Google configuration into your application string.xml file.
Code:
<string name="google_client_id">YOUR_GOOGLE_CLIENT_ID </string>
<string name="redirect_uri">Your_PACKAGE_NAME:/oauth2callback</string>
5) Add following into your application manifest file.
Code:
<activity android:name="net.openid.appauth.RedirectUriReceiverActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="YOUR_PACKAGE_NAME" />
</intent-filter>
</activity>
6) Add below dependency in app gradle
Code:
implementation 'net.openid:appauth:0.2.0'
Default theme of AGC UI
The default theme of AGC UI is nothing but the default user interface which is provided by the library. Following are the steps to use the default theme of AGC UI:
1) Comment or remove setContentViewMetho
2) Use initializeButton method to show or hide third party providers as shown below:
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main2);
initializeButton(true,true,true,true,true,true);
}
3) Enable app log and app name as shown below:
Code:
enableAppLogo(true);
enableAppName(true);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
appLogo( getResources().getDrawable(R.drawable.ic_body_builder),400,400);
appBackgroundColor("#fafafa");
appName("PANDAVAS",50,"#3e454f",typeface);
Byenabling them, we can provide our own app logo and name as shown above.
4) After user login using any provider the data we will receive in onActivityResult as shown below:
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data.getExtras() != null) {
Log.d(getClass().getName(), "RESPONSE IS " + data.getExtras().getString("response"));
Intent intent = new Intent(Main2Activity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
if(resultCode == Activity.RESULT_CANCELED){
// Do Anything
Toast.makeText(getApplicationContext(),"Canceled",Toast.LENGTH_LONG).show();
}
}
Result
Customization theme of AGC UI
We can also customize our own user interface using AGC UI. Following are the steps to customize:
1) Download the semi-circular radial menu library from the below link:
http://hasmukhbhadani.blogspot.com/2014/04/radial-menu-semi-circular-radial-menu.html
Get two files from this library that is SemiCircularRadialMenu and SemiCircularRadialMenuItem. Paste this two files in your project and modify them if you required.
2) Add the following code in our layout xml file:
Code:
<com.huawei.hmsui.arclib.SemiCircularRadialMenu
android:id="@+id/radial_menu"
android:layout_width="0dp"
android:layout_height="0dp"
android:padding="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
3) Add the following code in our Activity file:
Code:
// HUAWEI ID
mHuaweiId.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, HuaweiIdAuth.class), Constant.REQUEST_HU_SIGNIN_CODE);
}
});
Code:
// TWITTER LOGIN
mTwitter.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, TwitterAuth.class), Constant.REQUEST_TWITTER_CODE);
}
});
Code:
// GOOGLE LOGIN
mGoogle.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, GSignInActivity.class), Constant.REQUEST_GOOGLE_CODE);
}
});
Code:
// FACEBOOK LOGIN
mFacebook.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, FacebookAuth.class), Constant.REQUEST_FACEBOOK_CODE);
}
});
Code:
// EMAIL LOGIN
mHuaweiEmail.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, EmailAuthActivity.class), Constant.REQUEST_EMAIL_AUTH);
}
});
Code:
// PHONE LOGIN
mHuaweiPhone.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, PhoneRegisterActivity.class), Constant.REQUEST_PHONE_AUTH);
}
});
In the above code using startActivityForResult we can get the login functionality for providers.
4) After user login using any provider the data we will receive in onActivityResult same as default theme.
Result
AGC UI vs Firebase UI
Limitation of AGC UI
1) It will not support google sign in with underscore(_) in package name like:
com.example.demotest(supported)
com.example.demo_test(unsupported)
2) Update Email and update phone is not working in AGC for third party providers.
3) AGC UI only works for Android.
What we learn?
We learn how to integrate AGC UI and create two ways of login. It is an open source library so go crazy and build something useful.
GitHub
Very soon I am going to post the entire code on GitHub. So come back again to check it out.
FAQ
Question 1: While google signin we are getting Uri Mismatch Error
Answer:
1) Check redirectUri and client id in string.xml. RedirectUri in your string xml must be your_package_name+:/oauth2callback and client id must be android clientid.
2) Open AndroidManifest.xml and Check for android scheme in intent-filter of RedirectUriReceiverActivity. It must be your_package_name.
Question 2: While google signin getting 401(Authorization Error)
Answer: Check google developer console and confirm you are using client id of same application/project.
Question 3: Third party provider authentication is successful, but not able to Signing in AGC
Answer:
1) Check for provider on AGC console, it is enabled or not.
2) Check your app's authentication mode details by following
AGC console > My Project > Build > Auth Service > specific provider
For more reference
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-service-introduction
https://github.com/Huawei-DTSE-India-Delhi-NCR/AGC-UI-Auth

Related

How to Integrate HUAWEI Nearby Plugin to Cordova Project

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
Hello everyone, in this article, I will show how to integrate Huawei Nearby Plugin to a Cordova project.
Prerequisites
You should install npm, Node.js and Cordova CLI on your PC.
Pre-Installation
Configuring App Information in AppGallery Connect
Before you get started, you must register as a HUAWEI developer and complete identity verification on HUAWEI Developers.
Click to expand...
Click to collapse
Firstly, lets create an AppGallery Connect Project.
Sign in to AppGallery Connect and select My projects.
Click Add project.
Enter a project name and click OK.
After the project is created, the Project settings page is displayed. Before you use development capabilities provided by AppGallery Connect, you need to add an app to your project first.
In section Project settings > General information, click Add app.
On the Add app page, enter app information.
On the Project settings page, enter SHA-256 certificate fingerprint and then download the configuration file agconnect-services.json for Android platform.
A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in the AppGallery Connect. You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial for the certificate generation. Perform the following steps after you have generated the certificate.
Click to expand...
Click to collapse
Enabling Service
To use HUAWEI Nearby Service on your app, you first need to enable the service.
Sign in to HUAWEI Developers and click Console in the upper right corner. Go to HMS API Services > My APIs, select the project for which you want to enable HUAWEI Nearby Service, and click Add API from library. The API Library page is displayed.
Click Nearby Service.
On the Nearby Service page, click Enable to enable HUAWEI Nearby Service.
Sign the HUAWEI Nearby Service Agreement.
When you click My projects on the home page of AppGallery Connect to create a project for the first time, a dialog box will be displayed to prompt you to sign the HUAWEI Nearby Service Agreement (for details, please refer to AppGallery Connect Service and Agreement). If you have agreed to the HUAWEI Nearby Service Agreement, no such a dialog box will be displayed after you click Enable. For details, please refer to AppGallery Connect Agreement Signing Guide.
Click to expand...
Click to collapse
Go to HMS API Services > My APIs. The Nearby Service API is displayed.
Pre-installation steps end here. Basically, we created an AppGallery Connect project and enabled the Nearby Service. We also saved the SHA-256 certificate fingerprint to the project.
Installation
Firstly, open a command line and create a new Cordova project.
Bash:
cordova create HMSNearbyDemo com.huawei.medium.nearbydemo HMSNearby
This command will create a new directory named as HMSNearbyDemo and a new project named as HMSNearby inside it. You can change names as you wish.
The widget id property in config.xml file must be same with client > package_name value in agconnect-services.json file.
Click to expand...
Click to collapse
Go to project directory and add the android platform to the project.
Bash:
cd HMSNearbyDemo
cordova platform add android
Now, you need to add Huawei Nearby Plugin to the project. Run the following command in the root directory of your project to install it through npm.
Bash:
cordova plugin add @hmscore/cordova-plugin-hms-nearby
Copy agconnect-services.json file to <project_root>/platforms/android/app directory. In our case, project_root is HMSNearbyDemo folder.
Add keystore(.jks) to your project’s root directory.
You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial page for generating keystore file.
Click to expand...
Click to collapse
Create a file named as build.json in project’s root directory and fill the file according to your keystore information as in example below.
JSON:
{
"android": {
"debug": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
},
"release": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
}
}
}
Huawei Nearby Plugin requires minimum sdk version 21. If your minimum sdk version is lower than 21, set it as 21 in config.xml file. Otherwise, you can skip this step.
XML:
...
<platform name="android">
...
<preference name="android-minSdkVersion" value="21" />
</platform>
Finally, build the project.
Bash:
cordova build android
Using Huawei Cordova Nearby Plugin
Initially, we should request missing permissions from the user.
JavaScript:
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
// ...
// we have requested all permissions.
HMSNearby.requestPermissions([
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH,
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH_ADMIN,
HMSNearby.HMSPermission.PERMISSION_ACCESS_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_CHANGE_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_ACCESS_COARSE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_ACCESS_FINE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_READ_EXTERNAL_STORAGE,
HMSNearby.HMSPermission.PERMISSION_WRITE_EXTERNAL_STORAGE
]).then((res) => {
console.log("Request permissions result: " + res);
});
}
};
Now, all functionalities are ready to use. The Nearby Connection basic structure is shown in the image below. I will show you sample code parts for each step.
Starting Broadcasting
The sample code for starting broadcasting is as follows:
JavaScript:
async function startBroadcasting() {
try {
const name = 'NearbyBroadcast';
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startBroadcasting(name, serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
You can customize the name parameter.
Starting Scanning
The sample code for starting scanning is as follows:
JavaScript:
// starting scanning
async function startScan() {
try {
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startScan(serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
We need to register scan events. When a remote device is found or an already found device is lost, scan events will be triggered.
Registering Scan Events and Requesting Connection
Code part below sends a connection request to the remote device without asking the user when any device is found.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_FOUND, async (res) => {
console.log('listener :: EVENT_SCAN_ON_FOUND triggered: ' + JSON.stringify(res));
// request connect
const resRequest = await HMSNearby.requestConnect("NearbyScan", res.endpointId);
console.log("listener :: requestConnect: " + JSON.stringify(resRequest));
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_LOST, (res) => {
console.log('listener :: EVENT_SCAN_ON_LOST triggered: ' + JSON.stringify(res));
});
Registering Connection Events and Accepting Connection
When a connection established, both peers must accept the connection. Then, event EVENT_CONNECTION_ON_RESULT will be triggered with the success state.
JavaScript:
// registering connection events and accepting connection
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_ESTABLISH, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_ESTABLISH triggered: ' + JSON.stringify(res));
// Accept the connection request without notifying user.
HMSNearby.acceptConnect(res.endpointId);
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_RESULT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_RESULT triggered: ' + JSON.stringify(res));
if (res.statusCode == HMSNearby.StatusCode.STATUS_SUCCESS) {
// The connection was established successfully, we can exchange data.
}
});
Registering Data Events and Sending Data
We connected to remote peer successfully. Now, we can send any data to peer.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_RECEIVED, (res) => {
console.log('listener :: EVENT_DATA_ON_RECEIVED triggered');
if (res.dataType === HMSNearby.DataType.DATA_BYTES) {
const receivedBytes = res.data;
// data as number array
}
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_TRANSFER_UPDATE, async (res) => {
console.log('listener :: EVENT_DATA_ON_TRANSFER_UPDATE triggered: ' + JSON.stringify(res));
if (res.status === HMSNearby.TransferState.TRANSFER_STATE_SUCCESS) {
console.log('listener :: data transfer success');
}
});
try {
const bytes = [11, 22, 33, 44]; // any data in number array
const endpointIds = ['endpointId1', 'endpointId2']; // remote endpoint id list
await HMSNearby.sendBytes(bytes, endpointIds);
} catch(ex) {
alert(JSON.stringify(ex));
}
Disconnection
After all operations are done, we should simply call disconnect method. When a peer calls disconnect, event EVENT_CONNECTION_ON_DISCONNECT will be triggered on the other peer’s device.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_DISCONNECT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_DISCONNECT triggered: ' + JSON.stringify(res));
});
async function disconnect() {
try {
const endpointId = 'endpointId';
await HMSNearby.disconnect(endpointId);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
Conclusion
In this article, I integrated HMS Nearby Plugin to a Cordova project and showed the basic functionalities of Nearby Connection. I tried to explain connecting to peer, transferring data and disconnection functionalities with examples.
Thank you for reading, I hope it was helpful.

Beginner: Integration of Huawei Site Kit and Cloud DB in Android (Kotlin)

Introduction
In this article, we will be learning how to integrate the Huawei Site kit and Cloud DB integrations in Android using Kotlin. Using AGC Cloud DB service, Service Providers from multiple cities can manage their data through CRUD (Create, Read, Update and Delete) operations. Using Site Kit user can search nearby stores and check stores details.
Development Overview
You need to install Android Studio and I assume that you have prior knowledge about the Android and Kotlin
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later
Android studio installed.
HMS Core (APK) 4.x or later
Integration of Site Kit
Site Kit provides place search services including keyword search, nearby place search, place detail search, and place search suggestion, helping your app provide convenient place-related services to attract more users and improve user loyalty.
Step 1: To integrate Site kit, need to add the below library:
Code:
implementation 'com.huawei.hms:site:5.0.2.300’
Step 2: How to get API Key?
Create an app in AppGallery Connect enter all necessary information.
Generate and configure the signing certificate fingerprint.
Add the AppGallery Connect plug-in and the Maven repository in the project-level build.gradle file. Configure the signature file in Android Studio.
For details, refer to Preparations for Integrating HUAWEI HMS Core.
After configure project, you can find API key in below image.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 3: To initialize HMS Site kit:
searchService = SearchServiceFactory.create(this, Utils.getApiKey())
To fetch nearby stores based on user’s current location:
SearchServiceActivity.kt
Code:
intent.let {
val request = NearbySearchRequest().apply {
queryString=it.getStringExtra(AppConstants.REQUEST_QUERY).toString()
setQuery(queryString)
setLocation(
Coordinate(
it.getDoubleExtra(AppConstants.SERVICE_LAT_KEY, 0.0),
it.getDoubleExtra(AppConstants.SERVICE_LNG_KEY, 0.0)
)
)
}
imageString = it.getStringExtra(AppConstants.PROVIDER_IMAGE_KEY).toString()
searchService?.nearbySearch(request, searchResultListener)
}
Results
Note: For more details, refer Site kit integration procedure. Site kit- SDK integration
Integration of Cloud DB
In this scenario, we can learn about a database service that runs on a cloud and is accessible from anywhere. Find the following points for better understand:
How to use Cloud DB to develop applications?
How to read, write and query application data to Cloud DB?
This service provides the synergy database product that provides data synergy management capabilities between the device and the cloud, unified data models, and various data management APIs.
Cloud DB supplies us simply cloud database and our project work together successfully and we can take advantages of CRUD (Create, Read, Update and Delete) operations.
Prerequisites
To use the Cloud DB for build application service, you need to complete the following preparations:
You have registered an account on the AppGallery Connect console and passed real-name authentication.
You have created a project and application on the AppGallery Connect console.
You have enabled the Anonymous account authentication service for the application to use permissions of the authentication user.
You have installed Android Studio on the local host.
Enable Cloud DB Service
Before using the Cloud DB service, you need to enable it.
Log in to AppGallery Connect and click My Projects.
Select a project from the project list and click an app for which you need to enable the Cloud DB service.
In the navigation bar, choose Build > Cloud DB.
Click Enable now to enable the Cloud DB service.
Select the Data storage location.
After the service is initialized, the Cloud DB service is enabled successfully.
After the service is initialized, the Cloud DB service is enabled successfully.
Adding and Exporting Object Types
The following example shows how to create object types on the AppGallery Connect console and export the object type file in the Java format for Android application development.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add an object type.
3. In the navigation bar, choose Build > Cloud DB.
4. Click Add to navigate to the object type creation page.
5. Set Object Type Name to LoginInfo, and click Next.
6. Click “+Add Field”, add the fields as per your requirements and click Next.
7. (Optional) Click “+Add Index”.
8. Add permissions as follows and click Next. (For Everyone, upsert and delete access is not allowed).
9. Click OK. Object types are created and displayed in the object type list.
The created object types are displayed in the object type list.
Repeat the above steps to create to create multiple table.
10. Click “Export” button
11. Set the format of the file to be exported to JAVA.
12. Set the Java file type to Android.
13. Enter the package name in the JAVA file.
The package name can contain only the following three types:
Letters: A–Z or a–z, which are mandatory
Digits: 0–9
Special characters: underscore (_) and period (.)
15. Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project. The file that contains all object types in the version is exported to the local PC. The exported Java file will be added to the local development environment in subsequent steps.
Cloud DB Zone
You can create a Cloud DB zone on the AppGallery Connect console. Perform the following steps to set Cloud DB Zone Name.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add a Cloud DB zone.
3. In the navigation tree, choose Build > Cloud DB.
4. Click the Cloud DB Zones tab.
5. Click Add to go to the Cloud DB zone creation page.
6. Enter Your App Name in the Cloud DB Zone Name text box.
7. Click OK the created Cloud DB zones are displayed in the Cloud DB zone list.
Configuring the Development Environment
Add a Cloud DB SDK to the dependencies node in the build.gradle file in the Project/app directory.
Code:
implementation <strong>'com.huawei.agconnect:agconnect=database:1.2.3.301’</strong>
In the build.gradle file, set the compatibility mode of Java source code to JDK1.8.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
Adding Object Type Files
During application development, you can directly add the JAVA files exported from the AppGallery Connect console to the local development environment, and use the createObjectType() method in the AGConnectCloudDB class to define and create object types. Then you do not need to create object types for local application development.
Add all exported files to the local development environment.
Initialize Cloud DB. Use the createObjectType() method in the AGConnectCloudDB class to define and create object types.
Initializing
After adding an object type file, you can use the Cloud DB to develop an application. When developing an application, you need to initialize AGConnectCloudDB, and create Cloud DB zone and object types.
Initialize AGConnectCloudDB in an application’s CloudDBZoneWrapper
Code:
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
Obtain the AGConnectCloudDB instance and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance();
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
Create the Cloud DB zone configuration object and open the Cloud DB zone. Add the below code in CloudDBZoneWrapper class.
Code:
public void openCloudDBZoneV2() {
mConfig = new CloudDBZoneConfig(AppConstants.URBAN_HOME_SERVICES,
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
Log.w(TAG, "open clouddbzone success");
mCloudDBZone = cloudDBZone;
// Add subscription after opening cloudDBZone success
mUiCallBack.onInitCloud();
addSubscription();
}).addOnFailureListener(e ->
Log.w(TAG, "open clouddbzone failed for”));
}
Writing Data
You can use the executeUpsert() API to write one object or a group of objects to the current Cloud DB zone.
Add the below code in CloudDBZoneWrapper class.
Code:
public void insertDbZoneInfo(T objectInfo) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> upsertTask = mCloudDBZone.executeUpsert(objectInfo);
upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
mUiCallBack.onInsertSuccess(cloudDBZoneResult);
}).addOnFailureListener(e -> {
mUiCallBack.updateUiOnError("Insert table info failed");
});
}
Viewing Data
Data added on the application page will be stored on the cloud. After a listener for data changes is registered on the device, the device will be notified when there is any changes on the cloud, and the local data will be updated in time.
You can use the query condition together with the subscribeSnapshot() method to specify an object to be listened on. When the data of the object is changed, the device will be notified and the original data stored on the cloud will be synchronized to the device based on the data changes information obtained by snapshots.
Add the below code in CloudDBZoneWrapper class.
Code:
private OnSnapshotListener<T> mSnapshotListener = (cloudDBZoneSnapshot, e) -> {
if (e != null) {
Log.w(TAG, "onSnapshot" );
return;
}
CloudDBZoneObjectList<T> snapshotObjects = cloudDBZoneSnapshot.getSnapshotObjects();
List<T> dbZoneList = new ArrayList<>();
try {
if (snapshotObjects != null) {
while (snapshotObjects.hasNext()) {
T objectInfo = snapshotObjects.next();
dbZoneList.add(objectInfo);
}
}
mUiCallBack.onSubscribe(dbZoneList);
} catch (AGConnectCloudDBException snapshotException) {
Log.w(TAG, "onSnapshot:(getObject)");
} finally {
cloudDBZoneSnapshot.release();
}
};
Querying Data
The executeQuery(), addOnSuccessListener(), and addOnFailureListener() methods are used together to query data in asynchronous mode.
Add the below code in CloudDBZoneWrapper class.
Code:
public void queryAllData(CloudDBZoneQuery<T> query) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<CloudDBZoneSnapshot<T>> queryTask = mCloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<T>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<T> snapshot) {
processQueryResult(snapshot);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
mUiCallBack.updateUiOnError("Query failed");
}
});
}
Deleting Data
You can use the executeDelete() method to delete a single object or a group of objects. When deleting data, Cloud DB will delete the corresponding data based on the input object primary key and does not check whether other attributes of the object are consistent with the stored data. When a group of objects are deleted, the deletion operation is atomic. That is, objects in the list are either all deleted successfully or all fail to be deleted.
Add the below code in CloudDBZoneWrapper class.
Code:
public void deleteTableData(List<T> tableObject) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> deleteTask = mCloudDBZone.executeDelete(tableObject);
if (deleteTask.getException() != null) {
mUiCallBack.updateUiOnError("Delete service type table failed");
return;
}
mUiCallBack.onDelete(tableObject);
}
}
Editing Data
You can use the editService() method to edit professional’s details.
Add the below code in ManageServiceActivity.kt class.
Code:
override fun editService(listObject: ServiceType) {
val intent = Intent(this, AddServiceActivity::class.java)
intent.apply {
putExtra(AppConstants.CATEGORY_NAME, listObject.cat_name)
putExtra(AppConstants.PROVIDER_PH_NUM, listObject.phone_number.toString())
putExtra(AppConstants.PROVIDER_MAIL_ID, listObject.email_id)
putExtra(AppConstants.PROVIDER_COUNTRY, listObject.country)
putExtra(AppConstants.PROVIDER_ID, listObject.id)
putExtra(AppConstants.PROVIDER_NAME, listObject.service_provider_name)
putExtra(AppConstants.PROVIDER_CITY, listObject.city)
putExtra(AppConstants.PROVIDER_STATE, listObject.state)
}
startActivity(intent)
}
Results
Tips and Tricks
Always use the latest version of the library.
Always provide proper Roles to user in Object Types.
Note: For more details, please refer Cloud Db service integration documentation, Cloud DB- Introduction
Conclusion
By using Cloud DB you can connect with Database without the need of APIs. You can perform the CRUD operations and also can restrict user access for the tables. Easy to connect with the application. Also you can search nearby service (plumber, electrician, painter etc) using site kit like as etc.
Site Kit to fetch nearby stores.
Cloud DB service to add, delete and edit professional’s details.
References
Site Kit
Cloud DB- Applying for Cloud BD
Cloud DB- Introduction
Checkout in forum

Beginner: Integration of Huawei InAppMessage feature for promoting products in E-commerce app (React Native)

Overview
You can use App Messaging of AppGallery Connect to send relevant messages to target active users of your app to encourage them to use key app functions, or send attractive promotion activities to enhance user loyalty. App Messaging even allows you to customize your messages look and the way they will be sent, in addition to default message layouts. You can also define events for triggering message sending to your users at the right moment.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
In this article, I will show how user can promote their products using InAppMesseage service.
App Messaging allows you to send targeted messages based on user behaviour in your app to engage users and encourage certain user activities such as update, browse, subscribe and purchase. For example, you can use this service to send a promotion message of a product. When a user views product information, improving the sales and purchase rate.
Create Project in Huawei Developer Console
Before you start developing an app, configure app information in App Gallery Connect.
Register as a Developer
Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, refer to Registration and Verification.
Create an App
Follow the instructions to create an app Creating an App Gallery Connect Project and Adding an App to the Project. Set the data storage location to Germany.
React Native setup
Requirements
Huawei phone with HMS 4.0.0.300 or later.
React Native environment with Android Studio, NodeJs and Visual Studio code.
Dependencies
Gradle Version: 6.3
Gradle Plugin Version: 3.5.2
React Native CLI: 2.0.1
1. Environment set up, refer link.
2. Create project using below command.
Code:
react-native init project name
3. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
Generating a Signing Certificate Fingerprint
Signing certificate fingerprint is required to authenticate your app to Huawei Mobile Services. Make sure JDK is installed. To create one, navigate to JDK directory’s bin folder and open a terminal in this directory. Execute the following command:
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
This command creates the keystore file in application_project_dir/android/app
The next step is to obtain the SHA256 key which is needed for authenticating your app to Huawei services, for the key store file. To obtain it, enter following command in terminal:
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
After an authentication, the SHA256 key will be revealed as shown below.
Adding SHA256 Key to the Huawei project in App Gallery.
Copy the SHA256 key and visit AppGalleryConnect/ <your_AppMessage_project>/General Information. Paste it to the field SHA-256 certificate fingerprint.
Download the agconnect-services.json from App Gallery and place the file in android/app directory from your React Native Project.
Follow the steps to integrate the InAppMessage plugin to your React Native Application.
Enable the AppMessaging and Analytics kit from ManageAPIs as below.
Integrate the Hms-InAppMessage plugin:
User have react native version 16.6.0 install below command
Code:
npm install @react-native-agconnect/[email protected]
User have react native version 17.0.0 install below command
Code:
npm install --legacy-peer-deps @react-native-agconnect/appmessaging
Download the Plugin from the Download Link
Download ReactNative InAppMessage Plugin under node_modules/@react-native-agconnect of your React Native project, as shown in the directory tree below:
Code:
project-dir
|_ node_modules
|_ ...
|_ @react-native-agconnect
|_ ...
|_ appmessaging
|_ ...
|_ ...
Navigate to android/app/build.gradle directory in your React Native project. Follow the steps:
Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.4.1.300’)
Android setup:
Step 1: An example of your AndroidManifest.xml as follows:
Code:
<activity
android:name="com.huawei.agc.rn.appmessaging.example.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Step 2: Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Code:
defaultConfig {
applicationId "<package_name>"
minSdkVersion 19
/*
* <Other configurations>
*/
}
Creating an In-App Message​To send huawei in-app messages to users in specific scenarios, you need to create them in AppGallery Connect first and set the message layout and sending target
Procedure​1. Sign in to AppGallery Connect and click My projects.
2. Find and click your project.
3. Navigate to Grow > App Messaging and click New.
4. Set Name and Description
5. Set the layout and content and click Next.
Select the message type from the Type drop-down list box. Currently, the following options are supported: Pop-up, Image, and Banner.
6. Set the sending time and click Next.
7. Set conversion events.
Associate the display or tap of the in-app message with a conversion event. The conversion relationship will be displayed in statistics.
8. Click Save and Publish in the upper right corner to complete message creation.
In-App Message Display​The prerequisites for the React Native App Messaging plug-in to display in-app messages as follows:
1. The app must be running on the foreground.
2. A user triggers the event upon which an in-app message will be displayed. Then the React Native App Messaging plug-in synchronizes the message data from the AppGallery Connect server or obtains the message data from the local cache and determines whether to display the message.
Add Below Code in App.js:
The AGCAppMessaging.setFetchMessageEnable API can be called to enable or disable data synchronization from the AppGallery Connect server.
Code:
setFetchMessageEnable() {
AGCAppMessaging.getInstance().setFetchMessageEnable(true).then(result => {
Alert.alert("[setFetchMessageEnable] " + JSON.stringify(result));
this.createCustomView("setFetchMessageEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setFetchMessageEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setFetchMessageEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
The AGCAppMessaging.setDisplayEnable API can be called to set whether to enable message display.
Code:
setDisplayEnable() {
AGCAppMessaging.getInstance().setDisplayEnable(false).then(result => {
Alert.alert("[setDisplayEnable] " + JSON.stringify(result));
this.createCustomView("setDisplayEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setDisplayEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setDisplayEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
To add a custom view on the Android platform, add the following code to the onCreate method of your React-Native project /Android/MainApplication.java.
Code:
AgcAppMessagingModule.addCustomView();
Call the AGCAppMessaging.handleCustomViewMessageEvent for custom app message interactions. The following example calls the AGCAppMessaging.ON_MESSAGE_DISPLAY event once the custom app message has been shown:
Code:
componentDidMount() {
this.addMessageCustomViewListener();
}
addMessageCustomViewListener = () => {
AGCAppMessaging.getInstance().addMessageCustomViewListener((result) => {
Alert.alert(AGCAppMessaging.EventTypes.CUSTOM_VIEW + JSON.stringify(result))
/*
* Add Custom Message Event Handler method.
* When using custom app message layout, handle custom app message click events like below.
* gets eventType ( AGCAppMessaging.ON_MESSAGE_DISPLAY, AGCAppMessaging.ON_MESSAGE_CLICK, AGCAppMessaging.ON_MESSAGE_DISMISS, AGCAppMessaging.ON_MESSAGE_ERROR)
* and dismissType param( AGCAppMessaging.DISMISS_TYPE_CLICK, AGCAppMessaging.DISMISS_TYPE_CLICK_OUTSIDE, AGCAppMessaging.DISMISS_TYPE_AUTO, AGCAppMessaging.DISMISS_TYPE_SWIPE) when using AGCAppMessaging.ON_MESSAGE_DISMISS.
*/
this.handleCustomViewMessageEvent();
});
handleCustomViewMessageEvent() {
const customMessageDisplayReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISPLAY
}
const customMessageClickReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_CLICK
}
const customMessageDismissReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISMISS,
"dismissType": AGCAppMessaging.DismissTypes.DISMISS_TYPE_CLICK
}
const customMessageErrorReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_ERROR
}
AGCAppMessaging.getInstance().handleCustomViewMessageEvent(customMessageDisplayReq).then(result => {
Alert.alert("[handleCustomViewMessageEvent] " + JSON.stringify(result));
this.createCustomView("handleCustomViewMessageEvent : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[handleCustomViewMessageEvent] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[handleCustomViewMessageEvent] Error/Exception: ", JSON.stringify(err) + "")
});
}
class AGCAppMessaging{
constructor() {
this.emitter = new NativeEventEmitter(AGCAppMessagingModule);
}
static getInstance() {
if (!this.instance) {
this.instance = new AGCAppMessaging();
}
return this.instance;
}
addMessageDisplayListener(listener){
return subscription = this.emitter.addListener(
EventTypes.ON_MESSAGE_DISPLAY, listener
);
}
Test InAppMessage
Huawei In-app messages can only be displayed to users who have installed your officially released app. App Messaging allows you to test an in-app message when your app is still under tests. The testing procedure is as follows:
1. Obtain the anonymous application identifier (AAID) of the test device. For details, refer to Obtaining AAID.
2. Sign in to AppGallery Connect and select My projects.
3. Find your project from the project list and click the app for which you want to test an in-app message on the project card.
4. Navigate to Growing > App Messaging > Management, find the message that you need to test, and click Test in the Operation column.
5. Click Add test user and enter the AAID of the test device in the text box.
6. Click Save to set the in-app message to a test message and save the device as a test device.
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt.
2. Navigate to android directory and run the below command for signing the Apk.
Code:
gradlew assembleRelease
Output:
        
Tips and Tricks
Download latest HMS ReactNativeAppMessage plugin.
Add AAID to Test AppMessage in AppGalleryConnect.
For project cleaning, navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion:
In this article, we have learnt to integrate InAppMessage in React native project. We can integrate this service in different scenarios such as Travel, Education, Finance, Gaming and E-commerce apps to send the update, browse, subscribe and promote the product for better sales.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference:
App Messaging
Original Source

[Intermediate] Demystifying data messages and Analytics into Task Scheduler application using Huawei Push Kit and Analytics Kit

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Analytics
Analytics is a technique which is widely used in businesses today. It is essential for almost all the organizations to track the progress, user interactions and plan for the measures.
There are plenty of services available in the market which provides the access to assess the data and provide analysis report. I came across such service and tried to work on it. The results of the service are quite stable and quick.
I am talking about Huawei Analytics Kit.
Huawei Analytics kit offers data focused on intelligent decision making.
Huawei Analytics kit provides fast integration and convenient data collection.
Advantages
Simple and quick integration
Secure data-related services
Fast and convenient data collection
Real-time, comprehensive and intelligent analysis
Comprehensive user profiles
Assistance in effectively reaching users.
Push Service
Push services are widely used message sending/broadcasting service.
Which has many different ways and events to apply for different requirements.
Huawei Push kit offers different kind of message sending options as
Push Notification
Data Messages
We will be focusing on the Data Message in this article.
Data Messages
Data messages are data payloads which are handled at the device.
You can customize them in the form of key-value pair.
Use Case
This article will focus on the integration of Analytics and Push kit in the Task Scheduler application and will be showcasing how this can be helpful for the user to improve their businesses.
Development Overview
Prerequisite
1. Must have a Huawei Developer Account
2. Must have Android Studio 3.0 or later
3. Must have a Huawei phone with HMS Core 5.0.2.300 or later
4. EMUI 9.1.0 or later
Software Requirements
1. Java SDK 1.7 or later
2. Android 5.0 or later
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the Analytics and Push Kit API.
3. Download the agconnect-services.json file.
4. Create an Android project.
Integration
1. Add below to build.gradle (project) file, under buildscript/repositories and allprojects/repositories.
Maven {url 'http://developer.huawei.com/repo/'}
2. Add below to build.gradle (app) file, under dependencies to use the Analytics and Push kit SDK.
Code:
dependencies{
// Import the Push SDK.
implementation 'com.huawei.hms:push:5.1.1.301'
Import the Analytics, please add Analytics SDK
implementation 'com.huawei.hms:hianalytics:5.2.0.300'
}
Tip: Minimum android version supported for these kits is 19.
3. Add below permissions to manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE"/>
Development Process
Push Kit
Adding below for receiving the Data Messages:
Below needs to be added to AndroidManifest file under <Application>:
Code:
<service
android:name=".DemoHmsMessageService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
</intent-filter>
</service>
Obtaining Token
Push token is important to identify the application on a device and works a unique identifier.
Client calls the getToken method in HmsInstanceId to obtain the token from the push kit server which is further used by the server to send the Push notifications to the application.
I have created a method to my Main Activity for obtaining the token as below.
Code:
private void getToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Obtain the app ID from the agconnect-service.json file.
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/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 empty.
if(!TextUtils.isEmpty(token)) {
sendRegTokenToServer(token);
}
} catch (ApiException e) {
Log.e(TAG, "get token failed, " + e);
}
}
}.start();
}
// For logs
private void sendRegTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
Receiving Data Messages
To receive the data messages, we need to create a service and override the “onMessageReceived” method as below
Code:
import android.util.Log;
import com.huawei.hms.push.RemoteMessage;
import com.huawei.hms.push.HmsMessageService;
public class DemoHmsMessageService extends HmsMessageService {
private static final String TAG = null;
@Override
public void onMessageReceived(RemoteMessage message) {
Log.i(TAG, "onMessageReceived is called");
// Check whether the message is empty.
if (message == null) {
Log.e(TAG, "Received message entity is null!");
return;
}
// Obtain the message content.
Log.i(TAG, "get Data: " + message.getData()
+ "\n getFrom: " + message.getFrom()
+ "\n getTo: " + message.getTo()
+ "\n getMessageId: " + message.getMessageId()
+ "\n getSendTime: " + message.getSentTime()
+ "\n getDataMap: " + message.getDataOfMap()
+ "\n getMessageType: " + message.getMessageType()
+ "\n getTtl: " + message.getTtl()
+ "\n getToken: " + message.getToken());
Boolean judgeWhetherIn10s = false;
// If the message is not processed within 10 seconds, create a job to process it.
if (judgeWhetherIn10s) {
startWorkManagerJob(message);
} else {
// Process the message within 10 seconds.
processWithin10s(message);
}
}
private void startWorkManagerJob(RemoteMessage message) {
Log.d(TAG, "Start new job processing.");
}
private void processWithin10s(RemoteMessage message) {
Log.d(TAG, "Processing now.");
}}
Let’s send a Data Message to our App Users
In order to send the push notifications to the app users, we need to login to AGC.
Step 1: Choose your project
Step 2:
Goto > Grow > Push Kit
Note: Select data processing location if see the prompt to add one.
Step 3:
Goto > Notifications > Add Notifications
Step 4:
Create a new notification which needs to send to user and fill the below information.
Step 5:
Select Data message and fill the Name and Key-Value pair information.
Step 6:
Click on Test Effect and enter the token.
Click OK.
Step 7:
Scroll down and fill information for Push Scope as Specified device.
Fill Token for the device (Same as above).
Step 8:
Scroll down and fill information for Push time and other parameters.
Click Submit.
Step 9:
Click OK.
Analytics Kit
Initialization
We will be creating instance for the analytics to get the data on the console.
Code:
private Analystics(Context context){
this.context=context;
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(context);
}
public static Analystics getInstance(Context context){
if (analystics==null){
analystics=new Analystics(context);
}
return analystics;
}
Checking the Analytical data on AGC
Login to AGC
Step 1: Choose your project
Step 2:
Goto Huawei Analytics
Results
Goto >> Behaviour analysis >> Page analysis
Tips and Tricks
1. Events and attributes can be customized in Analytics kit.
2. Huawei Push Kit can work well with your own push server. So to create one, refer this.
3. Always integrate the latest version of the SDK.
4. Reports can be exported from AGC.
Conclusion
This article focuses on explaining the usage of Huawei Push kit-data message, with the help of Task Scheduler application and also showcase the analytical data to analyze the user behavior on the application which will further help to improve the user interaction.
References
GitHub
Push Kit
Analytics Kit
Orignal Source
can i send custom push message?
Can we send notification on specified time?

Know the latest weather! Integration of Huawei Push Kit in Application using React Native

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to subscribe the topic using integrating the Huawei Push Kit into React Native project.
Push notifications offers a great way to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application. Push Kit supports two types of messages: notification messages and data messages. You can send notifications and data messages to your users from your server using the Push Kit APIs or directly from the AppGallery Push Kit Console.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies and React Native Project Preparation
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Push Kit.
9. Environment set up, refer below link
https://reactnative.dev/docs/environment-setup
10. Create project using below command
Code:
react-native init projectname
11. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
12. Integrate the Hmspush plugin
Code:
npm i @hmscore/react-native-hms-push
13. Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
14. Add to dependencies.
Code:
Implementation project (': react-native-hms-push)
15. Project level build.gradle/buildScript directory set minSdkVersion to 19 or higher higher. In android/signingConfigs/config node, enter the keystore file credentials.
Code:
signingConfigs {
config {
storeFile file(<keystore_file_name>)
storePassword ‘<store_password>’
keyAlias ‘<alias>’
keyPassword ‘<key_password>’
}
}
16. Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
-Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
-Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
17. Navigate to android/settings.gradle and add the following.
Code:
include ':react-native-hms-push'
project(':react-native-hms-push').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-push/android')
18. Add below permissions in Android.manifest file.
Code:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development
Obtain a Token:
In order to push notifications to a device, you need to obtain a token. To get the token, use getToken method from HmsPushInstanceId module.
Code:
HmsPushInstanceId.getToken("")
.then((result) => {
this.log("getToken", result);
})
.catch((err) => {
alert("[getToken] Error/Exception: " + JSON.stringify(err));
});
Enabling/Disabling the message receiving
HmsPushMessaging.turnOnPush()
.then((result) => {
this.log("turnOnPush", result);
})
.catch((err) => {
This.log("[turnOnPush] Error/Exception: " + JSON.stringify(err));
});
Code:
HmsPushMessaging.turnOffPush()
.then((result) => {
this.log("turnOffPush", result);
})
.catch((err) => {
This.log("[turnOffPush] Error/Exception: " + JSON.stringify(err));
});
Add Push Notifications
To push a notification message to your device, navigate to your Huawei developer console and choose Project>Growing>Push Kit>Add notification.
Receiving the data messages
The data messages are not displayed directly on user devices. They have a data payload in a key-value pair. The data messages pushed by the server can be listened to by onRemoteMessageReceived() encapsulated in HmsPushEvent. The data message listener should be registered in componentDidMount() of Component to be used.
Code:
componentDidMount() {
this.listener = HmsPushEvent.onRemoteMessageReceived(event => {
const RNRemoteMessageObj = new RNRemoteMessage(event.msg);
const msg = RNRemoteMessageObj.parseMsgAllAttribute(event.msg);
console.log("Data message received : " + msg);
})}
Performing automatic Initialization.
Code:
HmsPushMessaging.setAutoInitEnabled(true)
.then((result) => {
this.log("setAutoInitEnabled", result);
})
.catch((err) => {
This.log("[setAutoInitEnabled] Error/Exception: " + JSON.stringify(err));
});
User can also send local notification messages.
Add the following code in AndroidManifest.xml :
Code:
<application ...>
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationActionsReceiver" />
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationScheduledPublisher"
android:enabled="true"
android:exported="true">
</receiver>
</application>
Modify and add following code according to need:
Code:
import { HmsLocalNotification } from'@hmscore/react-native-hms-push';
const notification = {
[HmsLocalNotification.Attr.title]: ‘Title of Notification',
[HmsLocalNotification.Attr.message]: 'Message is important', // (required)
[HmsLocalNotification.Attr.largeIcon]: 'ic_launcher',
[HmsLocalNotification.Attr.smallIcon]: 'ic_notification',
[HmsLocalNotification.Attr.bigText]: ‘bigText says HI',
[HmsLocalNotification.Attr.subText]: 'subText says hi',
[HmsLocalNotification.Attr.color]: 'black',
[HmsLocalNotification.Attr.vibrate]: false,
[HmsLocalNotification.Attr.vibrateDuration]: 1000,
[HmsLocalNotification.Attr.tag]: 'hms_tag',
[HmsLocalNotification.Attr.ongoing]: false,
[HmsLocalNotification.Attr.importance]: HmsLocalNotification.Importance.max,
[HmsLocalNotification.Attr.dontNotifyInForeground]: false,
[HmsLocalNotification.Attr.autoCancel]: false,
[HmsLocalNotification.Attr.actions]: '["Yes", "No"]'
};
// LocalNotification
HmsLocalNotification.localNotification(notification)
.then((result) => {
this.log("LocalNotification Default", result);
})
.catch((err) => {
This.log(
"[LocalNotification Default] Error/Exception: " + JSON.stringify(err)
);
});
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
5. Make sure you import:
import {HmsPushMessaging} from'@hmscore/react-native-hms-push';
6. For project cleaning navigate to android directory and run the below command.
gradlew clean
Conclusion
In this article, we can learn about how to integrate Push Kit in React native project. It offers reliable, responsive and precise push service. It helps the app to react to a wide range of usage scenarios, dramatically boosting user engagement.
Reference
Push Kit: Documentation
Push Kit: Codelab
Push Kit: Training Video

Categories

Resources