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

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:
Java:
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:
Java:
searchService = SearchServiceFactory.create(this, Utils.getApiKey())
To fetch nearby stores based on user’s current location:
SearchServiceActivity.kt
Java:
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.
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.
Java:
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.
Java:
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
Java:
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
Obtain the AGConnectCloudDB instance and create object types.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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
Read In Forum

Does CloudDB supports offline operations ?

What is the max size of data to be stored on Cloud DB?

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

Integrate AppGallery Connect's Cloud DB Service in Three Easy Steps

Cloud DB is a device-cloud synergy database product that provides data synergy management capabilities between the device and cloud, unified data models, and various data management APIs. In addition to ensuring data availability, reliability, consistency, and security, Cloud DB enables seamless data synchronization between the device and cloud, and supports offline app operations, helping you quickly develop device-cloud and multi-device synergy apps. For more information about Cloud DB, please click here.
Cloud DB can be easily integrated into apps through its SDK and APIs, ensuring security and reliability. During integration, the SDK and APIs ease your workload by performing server setup, deployment, and O&M for you.
Now, let’s first take a look at how to quickly integrate Cloud DB in Android apps. You only need to perform the following three steps:
1. Create an object type and a Cloud DB zone.
2. Export the object type and perform account authentication.
3. Integrate the Cloud DB SDK into your Android project and call APIs to add, delete, modify, or query data.
1. Creating an Object Type and a Cloud DB Zone​Cloud DB is still in beta, so you’ll need to send an email to apply for the service. For more details on how to do so, please read the following documentation.
1.1. What Is an Object Type?​Simply put, each object type corresponds to a table used to store data in your database. Think of it as creating an Excel file to store data, whereby each sheet in the Excel file is equivalent to an object type in Cloud DB.
1.2. What Is a Cloud DB Zone?​A Cloud DB zone is an independent data storage zone. Multiple Cloud DB zones are independent of each other. Going back to the Excel file analogy, imagine that you’re a teacher responsible for multiple classes, and you record the scores of students in each class in an Excel file. Each Excel file contains a student information sheet and a score sheet that are independent of each other. A Cloud DB zone is akin to an Excel file in this analogy.
1.3. Creating an Object Type​Before you start, apply for and enable Cloud DB by performing the following:
1. Sign in to AppGallery Connect and click My projects. Select your project and app. Go to Build > Cloud DB, click the ObjectTypes tab, and create an object type.
{
"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"
}
2. Create an object type named StudentInfo. Please remember to set the primary key and select the upsert and delete permissions for the Authenticated user.
1.4. Creating a Cloud DB Zone​On the Cloud DB Zones tab page, click Add, enter the name of the Cloud DB zone, and click OK.
Before You Start​When using Cloud DB, you need to export the object type first.
You need to export the object type created in the previous step to your local Android project. This synchronizes data between your Android project and Cloud DB.
Remember to place the exported object type in your Android project. In the example below, I placed the object type in the model directory.
Integrating Cloud DB in Your Android Project​1. Integrating the Cloud DB SDK​1. In AppGallery Connect, click My projects, and click a project card. Go to Project settings > General information, and download the agconnect-services.json file in the App information area. Then, place the JSON file under the app directory in your Android project.
2.Configure the project-level build.gradle file.
XML:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3. Configure the app-level build.gradle file.
XML:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
...
android {
......
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
...
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.300' // Auth Service of AppGallery Connect, for account authentication.
implementation 'com.huawei.agconnect:agconnect-database:1.2.3.301' // Cloud DB SDK.
}
1.1 Preparations
Cloud DB places operation restrictions on users. Only authenticated users can add, delete, and modify data. Therefore, you’ll need to integrate Auth Service first.
Enable Auth Service in AppGallery Connect. Using anonymous account authentication as an example, click My projects, click a project card, and go to Build > Auth Service to enable it.
Sample code for enabling anonymous account authentication:
Java:
AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
}
});
2. Completing Initialization​The initialization consists of three parts: initializing Cloud DB, creating an object type, and creating and opening a Cloud DB zone.
1. Define required parameters in onCreate:
Java:
private AGConnectCloudDB mCloudDB;
private CloudDBZoneConfig mConfig;
private CloudDBZone mCloudDBZone;
2.Initialize AGConnectCloudDB.
Java:
AGConnectCloudDB.initialize(this);
3.Obtain an AGConnectCloudDB instance and create an object type.
Java:
mCloudDB = AGConnectCloudDB.getInstance();
try {
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "createObjectType Failed " + e.getMessage());
}
4. Create and open a Cloud DB zone.
Java:
Config = new CloudDBZoneConfig("classs1",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
CloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "openCloudDBZone failed: " + e.getMessage());
}
Note that you can also use the asynchronous openCloudDBZone2 method. The detailed operations are not described here. For details, please refer to:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-clouddb-get-started#h1-1594008398022
3. Using Cloud DB Functions​Once you have completed authentication, you can perform related operations on Cloud DB. The following uses the query operation as an example:
1. In AppGallery Connect, insert two records — test1 and test2 — for testing.
2. Go back to your Android project and call executeQuery to query all data.
Java:
Task<CloudDBZoneSnapshot<StudentInfo>> queryTask = mCloudDBZone.executeQuery(
CloudDBZoneQuery.where(StudentInfo.class),
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<StudentInfo>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<StudentInfo> snapshot) {
//
CloudDBZoneObjectList<StudentInfo> InfoCursor = snapshot.getSnapshotObjects();
ArrayList<StudentInfo> infoList = new ArrayList<>();
StudentInfo studentInfo = new StudentInfo();
try {
while (InfoCursor.hasNext()) {
studentInfo = InfoCursor.next();
infoList.add(studentInfo);
}
Log.i("CloudDB", "query success: " + JSONArray.toJSONString(studentInfo));
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "query failed: " + e.getMessage());
}
snapshot.release();
}
});
3. Then, you can view the corresponding query data in Logcat.
4. You can refer to the configuration guide and API reference to learn more about the add, delete, and modify operations:
Configuration guide:
https://developer.huawei.com/consum...allery-connect-Guides/agc-clouddb-insert-data
API reference:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb
Summary​You can use Cloud DB after performing just three easy steps:
1. Create an object type and a Cloud DB zone.
2. Export the object type to an Android project.
3. Integrate the SDK into the Android project and call related APIs.
Once you have completed these steps, you will have integrated a database system into your app, without having to perform any setup or deployment operations. Currently, Cloud DB is still free to use.
Cloud DB links:
Development guide:
https://developer.huawei.com/consum...llery-connect-Guides/agc-clouddb-introduction
API reference:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb
Demo:
https://github.com/AppGalleryConnect/agc-demos/tree/main/Android/clouddb-java

[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?

Use Keyring for Sign-in Across Different Apps and Platforms

It's common for an app developer to develop multiple apps across different platforms. However, an issue that arises is that when signing in to different apps or the same app across different platforms on the same device, users usually needs to repeatedly enter their account name and password even if the same account is used, which has a negative impact on user experience.
Keyring provides developers with the ability to share user authentication credentials across different apps and app platforms, thus creating a seamless sign-in experience for users. In this article I will explain how to integrate Keyring and implement cross-platform & cross-app sign-in.
Preparations​
Before integrating the Keyring SDK, you'll need to perform the following preparations:
1. Configure app information in AppGallery Connect.
2. Create an Android Studio project and configure the Maven repository address. If you are using Android Studio, you can integrate the HMS Core SDK via the Maven repository. Before you start developing an app, integrate the HMS Core SDK into your Android Studio project.
3. Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Integrating the Keyring SDK​
After completing the preparations, let's look at how to integrate the Keyring SDK.
1. Open the app-level build.gradle file in the 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"
}
2. Add a build dependency on the Keyring SDK in the dependencies block.
Find the dependencies block in the build.gradle file, add a dependency on the Keyring SDK in the block, and click Sync Now to make Android Studio synchronize the project.
Code:
dependencies{
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation "com.huawei.hms:keyring-credential:6.1.1.302"
}
Scenario Simulated by the Sample Code​
​The sample code provides two sample apps, which are App1 and App2.
App1 simulates the sign-in operation, and calls APIs of Keyring to save the user sign-in credentials. App1 then shares these credentials with App2.
App2 calls APIs of Keyring to query available credentials, and calls the getContent API to obtain the user's sign-in password.
To make the sample code work, we need to create two apps in AppGallery Connect, download the agconnect-services.json files of the two apps, and place the files in the corresponding Android Studio projects of App1 and App2. Refer to "Preparations" for details.
Preparing Information​
We need to collect the information listed below for use later on.
We need to set the sharing relationship in the code for App1 and App2. Therefore, we need to query and record the package names and signing certificate fingerprints of App1 and App2. For details about how to obtain the signing certificate fingerprint, please refer to "Preparations."
Development Practice​
1. Configure App1 to save user credentials using the Keyring SDK.
App1 simulates the app sign-in operation, the sample project has only one activity, that is, MainActivity, in which most code lines are used to implement the sign-in screen and basic sign-in logic. This activity has a member object of the CredentialClient type, which is the operation object for accessing Keyring and is initialized in the onCreate method of the activity.
Code:
mCredentialClient = CredentialManager.getCredentialClient(this);
Then, implement the login method for the onClick method of the Login button.
Code:
private void login(View view) {
if (!checkInput()) {
return;
}
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
// connect server to login.
saveCredential(username, password,
"app2", "com.huawei.hms.keyring.sample.app2",
"XX:XX:XX:XX:XX:XX",
true);
}
At the beginning of the login method, the checkInput method is called to check the validity of the user name and password in the input text boxes. In most cases, the service logic will connect to the background and use the user name and password for sign-in. The sample code does not include the code for implementing this. Here, we assume that the user name and password are correct, and that sign-in is performed successfully in the background.
The next step is to call the saveCredential method to save the credentials. The saveCredential method is a simple method encapsulated to highlight the input parameters. Such input parameters include the user name, password, information related to the sharing target app. It also includes the configuration specifying whether user authentication is required during credential reading.
App2's package name and certificate fingerprint recorded earlier will be used here. When calling the saveCredential method, we need to pass the package name and certificate fingerprint of App2 to the method as parameters.
Code:
private void saveCredential(String username, String password,
String sharedToAppName, String sharedToAppPackage,
String sharedToAppCertHash, boolean userAuth) {
AndroidAppIdentity app2 = new AndroidAppIdentity(sharedToAppName,
sharedToAppPackage, sharedToAppCertHash);
List<AppIdentity> sharedAppList = new ArrayList<>();
sharedAppList.add(app2);
Credential credential = new Credential(username,
CredentialType.PASSWORD, userAuth,
password.getBytes());
credential.setDisplayName("nickname_" + username);
credential.setSharedWith(sharedAppList);
credential.setSyncable(true);
mCredentialClient.saveCredential(credential, new CredentialCallback<Void>() {
@Override
public void onSuccess(Void unused) {showMessage("save credential to Keyring success");}
@Override
public void onFailure(long errorCode, CharSequence description) {
showMessage("save to Keyring failed" + " ====" + errorCode + ":" + description);
}
});
}
In the saveCredential method, we use the package name and certificate fingerprint of App2 to create an app object app2. Then, we place this object in sharedAppList of AppIdentity and use the list as a parameter of the credential object. After that, we create a password-type credential object, and call a series of set methods for this object to set the sharing app list and other configurations of the credentials. Finally, we call the saveCredential method of the Keyring operation object mCredentialClient to save the credentials. We also need to set the callback methods called when credentials are successfully saved or failed to be saved.
We have now saved the credentials in Keyring.
2. Configure App2 to use the Keyring SDK to query and read credentials.
App2 simulates the sign-in operation of another app made by the same developer. App2 can use the Keyring SDK to query credentials saved by itself earlier and credentials shared with it by the specified app, and read the credential content for seamless sign-in. App2 also has only one activity, that is, MainActivity, which simulates the sign-in screen. App2, like App1, also defines a member object mCredentialClient of the CredentialClient type and uses the object as the operation object for accessing Keyring. The operation object is also initialized in the onCreate method of the activity. The queryCredential method is called at the end of the onCreate method to query available credentials.
Now, let's look at how to implement the queryCredential method.
Code:
private void queryCredential() {
final AndroidAppIdentity app1 = new AndroidAppIdentity("app1",
"com.huawei.hms.keyring.sample.app1",
"XX:XX:XX:XX:XX:XX"
);
List<AppIdentity> trustedOwnerList = new ArrayList<>();
trustedOwnerList.add(app1);
mCredentialClient.findCredential(trustedOwnerList, new CredentialCallback<List<Credential>>() {
@Override
public void onSuccess(List<Credential> credentials) {
if (credentials.isEmpty()) {
noAvailableCredential();
} else {
MainActivity.this.setCredentialList(credentials);
}
}
@Override
public void onFailure(long errorCode, CharSequence description) {
noAvailableCredential();
}
private void noAvailableCredential(){showMessage("no shared credential");}
});
}
When preparing for SDK integration earlier, we recorded the package name and certificate fingerprint of App1. Now we use the information in the queryCredential method to create an AndroidAppIdentity object representing App1. Then, place the object in trustedOwnerList of AppIdentity.
Next, we call the findCredential method of the Keyring operation object mCredentialClient and pass trustedOwnerList and the result callback to the method. The findCredential method will query and list credentials that are available to this app. Such credentials include those stored by this app and those shared with this app by other apps specified in trustedOwnerList. In the sample code of App2, the findCredential method will query credentials saved by App2 and credentials shared with App2 by App1.
Available credentials exist if the onSuccess method is called and the credentials parameter is not empty. Then, the setCredentialList method will be called to display the credential list in the RecyclerView component on the app screen.
The choose method in the CredentialHolder class will be called if one of the credentials displayed on the screen is chosen. In the choose method, the selected credential object will be assigned to the member object mChooseCredential. After the user taps the Login button on the app screen, the login method will be called.
Code:
private void login(View v) {
if (mChooseCredential == null) {
showMessage("please_choose_account");
return;
}
mChooseCredential.getContent(new CredentialCallback<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// String password = new String(bytes);
showMessage("Login success");
}
@Override
public void onFailure(long l, CharSequence charSequence) {
showMessage("Get password failed");
}
});
}
In the login method, if mChooseCredential is not empty, the getContent method of the chosen credential object will be called to obtain the credential content. When calling the getContent method, we also need to pass the result callback to it.
The bytes parameter in the onSuccess method indicates the credential content, that is, the user sign-in password saved by App1. In a real app, we can directly use the password for sign-in, creating a seamless sign-in experience.
That's all for this tutorial. You can visit the Keyring official website for more information.
Does it support for quickApp?
Basavaraj.navi said:
Does it support for quickApp?
Click to expand...
Click to collapse
Yes, it supports quick apps.

Categories

Resources