Cloud DB configuration and an example with Kotlin - Huawei Developers

Cloud DB Configuration and Example
{
"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"
}
Hi Everyone, today I will try to explain Cloud DB and its features also You can find code examples under required topics. You can download my project that developed using Kotlin from link where is at the end of Page.
What is Cloud DB ?
Cloud DB is an relational database based on Cloud . In addition to the easy of use, attracts developers with its management and a user-friendly interface. If you don’t have server When starting to develop an app, you will definitely use it .It includes many features for developers like data storage, maintenance, distribution, object-based data model. Also it is free.
Currently, Cloud DB is in Beta version. It must be activated before using so Developers have to request the activation of the service by sending an e-mail to [email protected] with the subject as “[Cloud DB]-[Company name]-[Developer account ID]-[App ID]”
! I said before Cloud Db is an relational database . The only drawback is that Developers can’t query in multiple object type that is called Table in normal relational database system.
Cloud DB Synchronization Modes
Cloud DB contains two development modes different from together. I used cache mode in related example.
Cache Mode : Application data is stored on the cloud, and data on the device is a subset of data on the cloud. If persistent cache is allowed, Cloud DB support the automatic caching of query results on the device
Local Mode : Users can operate only the local data on the device, while device-cloud and multi-device data synchronization cannot be implemented.
Note : The cache mode and local mode can be used together or separately.
Cloud Db has stronger technical specifications than other cloud service providers. You can read all specifications following link
Cloud DB Structure and Data Model
Cloud DB is an object model-based database with a three-level structure that consists of Cloud DB zone, object type, and object.Cloud db may include many different database as you see. All Database are independent from others.
Cloud DB Zone
As Developers , you can think it as Database. It consist of object types that contains data. Each Cloud Zone can be different object type.
Object Type
Object Type stores data and includes data features . It is same as Table in Relational Database .Each object type must include at least one column as primary key. Object Types include many type like others database’s table for instance string, long, float, date, Boolean and more. You can learn all data types of Cloud DB visiting link.
Developers can import data from your device . All data must be in the json file.in addition They can export data from table/tables as json file.
Object
Objects are called data record. These records are stored in Object types.To learn declarations steps and restriction with detail ,please follow link.
User Permissions
Cloud DB can authenticate all users’ access to ensure security of application data. Developers specify these roles and ensure data security.
Cloud DB defines four roles: Everyone, Authenticated user, Data creator, and Administrator, and three permissions: query, upsert (including adding and modifying), and delete.
Everyone : They just read data that come from Cloud zone. Upsert and delete rules can’t be added. but query permission can be changed.
Authenticated user : these users can only read data by default but developers can change their permissions .
Data Creator : The information about data creators is stored in the system table of data records. This role has all permissions by default and can customize the permissions.
Administrator : This role has all permissions by default and can customize the permissions. An administrator can manage and configure the permissions of other roles.
Note : If you want to use the permissions of Authenticated user when developing applications on the device, you need to enable auth service to sign in operation.
How to use Cloud db in an app
After this part I try to explain cloud db integration steps and its functions. I will share related code block under topic but If you want to test app , You can get related source(I will put link under article.).
Note : Also app was developed using Kotlin.
Before start to develop , you need to send mail to enable Cloud DB . I explained before How to do this so I don’t write again .After open Cloud db, create cloud zone and then Object type to store data.
agconnect-services.json file must be created. To learn how to create it please visit link .
Code:
//Cloud DB
implementation 'com.huawei.agconnect:agconnect-database:1.2.1.301'
//Auth Service
implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
implementation 'com.huawei.hms:hwid:4.0.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.3.1.300'
After enable cloud DB , Cloud Zone and Object type can be created. In this Example I used this object type. First field is primary key of Object type.
When the Object type creating is finished , we need to export Object type information from Cloud DB page to use in app.
After click export button , you need to write app’s package name after that document will be created .You can export related information as Json or Java file.
Before start to develop cloud DB functions like upsert , delete or query , developers need to initialize AGConnectCloudDB, create a Cloud DB zone and object types.App needs to initialize before using. All developers must follow sequence of Cloud DB.
AGConnectCloudDB.initialize(context)
Initialize AGConnectCloudDB
Open CloudDB zone
Before starting with cloud DB zone, all initialization must be finished .
Code:
//CloudDB's initialize method is called, this method is called inside manifest file.
AGConnectCloudDB.initialize(applicationContext)
private val cloudDB = AGConnectCloudDB.getInstance()
cloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo())
private val cloudDBZoneConfig = CloudDBZoneConfig()//it must be created before open Cloud DB zone
private val cloudDbZone = cloudDB.openCloudDBZone(cloudDBZoneConfig,true)
Open CloudDBZone
Opening cloud db zone is important part of every project because all developers have to open cloud db zone to manage data. All transactions are developed and run using CloudDBZone object. If you check app , you can learn in a short time how to use it.
Code:
/* 1.Parameter is used to send cloud DB zone name You need to write cloudDBZone name into first parameter
2.Parameter is used to send CloudDB Synchronization Modes
3.Parameter is used to send Access property like CLOUDDBZONE_PUBLIC
after create CloudDBZoneConfig , CloudDBZone can be opened.
*/
cloudDBZoneConfig = CloudDBZoneConfig("BookComment", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC)
cloudDbZone = cloudDB.openCloudDBZone(cloudDBZoneConfig,true)
Notes :
All Cloud db operations (Upsert,Query,Delete) must be run when the Cloud DB zone is opened. Otherwise, the write operation will fail.
Many object can be inserted or deleted at the same time If all objects are the same object type.
Select Operation
Cloud DB uses the executeQuery to get data from Cloud .
Code:
// It is used to get all comment from Cloud db zone.
val cloudDBZoneQueryTask =cloudDbZone.executeQuery(CloudDBZoneQuer
.where(Comment::class.java)
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY)
If you want to get specific data , you can specify related column and restriction using method instead of SQL. Cloud Db doesn’t support sql.It includes many type of function to query operations like greaterThan(),greaterThanOrEqual(),orderByAsc(),etc.
More than one restriction can be used in one query.
Code:
val cloudDBZoneQueryTask =cloudDbZone.executeQuery(CloudDBZoneQuery
.where(Comment::class.java).contains("BookName",bookName),
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY)
for more example ,please visit link
Insert & Update Operations
Cloud DB uses executeUpsert to insert and update operation. If an object with the same primary key exists in the Cloud DB zone, the existing object data will be updated. Otherwise, a new object is inserted. We can send model to insert or update operation.
Code:
var upsertTask : CloudDBZoneTask<Int> = cloudDbZone.executeUpsert(newComment)
Delete Operation
executeDelete() or executeDeleteAll() functions can be used to delete data.ExecuteDelete() function is used to delete a single object or a group of objects,executeDeleteAll() function is used to delete all data of an object type.Cloud DB will delete the corresponding data based on the primary key of the input object and does not check whether other attributes of the object are consistent with the stored data.
Code:
val cloudDBDeleteTask = cloudDbZone.executeDelete(selectedItem)
When you delete objects, the number of deleted objects will be returned if the deletion succeeds; otherwise, an exception will be returned.
All CRUD operations are in WrapperClass , you can see it
More information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201381349122390461&fid=0101187876626530001

Well explained, How much data we can save into cloud DB.

Very useful, thank you very much

Very well explained, what are the limitations for the storage?

Related

[AppsUP] Frequently Asked Questions About Huawei Analytics Kit

AppsUP contest has been launched since June 30. Many developers meet the following issues in the process. If you also have the same issue which needs to be resolved, these questions in the list will be timely help. Any doubts or questions about Analytics Kit, this post can be a reference.
Q: When I integrate analysis kit, the compilation errors occurs in React Native Version 0.59.8
A: If you are migrating your app to HMS, suggest you to cross reference your original project and simply add the line to the buildscript/repositories and allprojects/repositories blocks.
The details you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248163576960163&fid=0101187876626530001
Q: Can we change the data storage for Advanced Analytics and How?
A: Till now there is no option to change the Data Storage Location, but you can reset it by deleting your existing app and recreating the app. Then you will see the option to set data storage location option during configuring the developer option. At the same time you must be careful about setting of Data Storage Location because once it set you can't change or modify it.
Q: Huawei analysis shows that the user data does not match the user data displayed on the background of Huawei analysis.
A: According to Huawei analysis, all users are virtual users.
If an application is uninstalled and then reinstalled on a mobile phone, the number of users is counted as two.
Therefore, the number of users calculated by Huawei analysis is greater than or equal to the actual number of users.
Q: If developers need to report some customized user property, which API can be use?
A: You should use "setUserProfile" method of this class: com.huawei.hms.analytics.HiAnalyticsInstance
Attributes will be reported to AGC Analytics and will be usable.
API description is as below:
{
"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"
}
link:
https://developer.huawei.com/consumer/en/doc/development/HMS-References/3021008#setUserProfile
Q: How to export data to an app server through the data export API provided by the Analytics Kit gateway?
A: Before calling Analytics Kit APIs, you need to obtain the token for authentication. This process involves three parameters, wherein: client_id is the app ID obtained during app creation, client_secret is the password for the app ID that can be queried on HUAWEI Developers, grant_type has a fixed value of client_credentials. In the following example, the getToken() method sends a POST request encapsulating the HTTP tool class to obtain the token and convert the obtained token into an object for subsequent authentication.
More details, you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201302699264940068&fid=0101187876626530001
Q: Integrated Analytics Kit, Why Does the Server Return Error Code 402 When Data Fails to Be Reported?
A: Developers have modified the agconnect-services.json configuration. As a result, the app fails to obtain the AGC token.
Q: Where Is Entry Menu of HUAWEI Analytics Kit?
A: HUAWEI Analytics Kit has been enhanced to provide the cross-platform analysis capabilities, allowing one-stop, unified analysis of Android and iOS users. It looks into the user-centric analysis and helps you understand user behavior on the Android and iOS platforms. For easier access, the entry menu on AppGallery Connect has been changed from Analyze > Advanced analysis (beta) to My projects > HUAWEI Analytics. You can view the overall analysis report or analysis report specific to a certain platform or app in your project. You can even compare user behaviors of different apps and platforms.
Q: Why reporting of custom events fails when I was conducting cross-platform data analysis using User-ID?
A: Event ID definition rule of HUAWEI Analytics Kit: An event ID cannot be left empty or contain spaces. It can consist of a maximum of 256 characters including digits, letters, and underscores (_) but cannot start with a digit. In addition, its value cannot be the same as the ID of an automatically collected event.
Therefore, you can change Purchase Test to Purchase_Test or any other value that complies with the preceding rule.
If you have multiple iOS and Android apps in a project, you can use the filter to view the overall analysis report or detailed report of an app. You can even link users' activity data from different devices by using User-ID to obtain cross-platform analysis data. For details about cross-platform analysis, see:
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/3021001
Q: I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
A: When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Q: What should I do if data reporting fails and the server returns error code 401?
A: Cause Analysis:
Possible causes are as follows:
HUAWEI Analytics Kit has not been enabled.
The obtained agconnect-services.json file is not the original file.
The debug mode has not been successfully enabled.
The Logcat log data on the device is not reported successfully.
Solution:
To correct the fault, perform the following steps:
Check whether HUAWEI Analytics Kit has been enabled and whether it has been turned on (default) in the API management.
Check whether the agconnect-services.json file is the original file without any modification.
Check whether the debug mode is enabled.
Check whether the log data is reported successfully. If the log contains resultCode: 200, the data is reported successfully. Possible causes are as follows:
Case 1: The tools:node parameter is set to "replace" (that is, tools:node="replace"). This causes the app configuration to conflict with AppGallery Connect SDK configurations, and therefore an exception occurs when the AppGallery Connect API is called to obtain the token.
Case 2: The configuration for excluding HUAWEI Analytics Kit from obfuscation is not added before you compile the APK. As a result, an exception occurs during the running of the APK.
Open the obfuscation script file of your project.
Add configurations to exclude HUAWEI Analytics Kit from obfuscation.
Set tools:node to "merge" (that is, tools:node="merge").
Manually write all information in the AndroidManifest.xml file of AppGallery Connect to the AndroidManifest.xml file of your app.
Code:
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agconnect.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
Related articles you can refer:
[AppsUP] Frequently Asked Questions About Huawei Account Kit
[AppsUP] Frequently Asked Questions About Huawei Map Kit
[AppsUP] Frequently Asked Questions About Huawei Push Kit
More doubts or questions about Analytics Kit, leave your comment below or ask your questions in HUAWEI Developer Forum.

Exploring the Huawei Health Kit: Data Controller

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201326975480310022&fid=0101246461018590361
Hello everyone , in this article we’re going to take a look at the Huawei Health Kit features so we can easily put these features to our apps.
Health app industry have shown an important increase in recent years.The software and healthcare industry are working together to find the latest technology products for the needs of patients and families.Huawei offers high technology service for the health and fitness app ecosystem with HealthKit and HiHealthKit service.Huawei and third-party partner capabilities track and customize all aspects of better living.
Data storage : Provides a platform for users to store their fitness and health data.
Data openness : Provides a wide range of APIs for writing and reading speed, positioning, blood sugar level, and other data.
Data interaction : Enables you and your users to agree on data access, guaranteeing proper use and security of personal data.
HealthKit:
https://developer.huawei.com/consumer/en/hms/huawei-healthkit
HiHealth:
https://developer.huawei.com/consumer/en/hms/huawei-healthkit
We will examine the differences between HealthKit and HiHealth in our next articles.I created a sample app which I’ve open-sourced on GitHub for enthusiasts who want to use this service.
https://github.com/tualdev/hms-health-kit-demo
Setting up the Health Kit
You’ll need to do setup before you can use the Health Kit.You can follow the official documentation on how to prepare app and enable Health Kit on App Gallery Connect.
Also you can follow this blog post to integrate your apps with Huawei HMS Core:
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98
I’ll show you how to implement Data Controller features in this article for your android projects.Let’s get started!
Add the required dependencies to the build.gradle file under app folder.We need some dependencies.
Code:
implementation 'com.huawei.hms:hwid:4.0.1.300'
implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.3.1.300'
implementation 'com.huawei.hms:hihealth-base:5.0.0.300'
Add the required permissions to the AndroidManifest.xml file under app/src/main folder.
Code:
<uses-permission android:name="android.permission.INTERNET" />
You need to give some permissions after applying for HealthKit in service cards area.The applied permissions will be displayed on the user authorization page.
{
"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"
}
Let’s continue by coding Data Controller functionalities in our project.
Sign-in before using Data Controller
Firstly, we need to configure Huawei ID sign in.After that, we will start sign intent while using startActivityForResult method.We added also some scopes to apply for. The following only shows an example. You need to add scopes according to your specific needs.
Code:
huaweiIdAuthParamsHelper = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
val scopeList = listOf(
Scope(HwIDConstant.SCOPE.SCOPE_ACCOUNT_EMAIL),
Scope(HwIDConstant.SCOPE.ACCOUNT_BASEPROFILE),
Scope(Scopes.HEALTHKIT_STEP_BOTH),
Scope(Scopes.HEALTHKIT_HEIGHTWEIGHT_BOTH),
Scope(Scopes.HEALTHKIT_HEARTRATE_BOTH)
)
huaweiIdAuthParamsHelper.setScopeList(scopeList)
authParams = huaweiIdAuthParamsHelper.setAccessToken().createParams()
authService = HuaweiIdAuthManager.getService(this, authParams)
HEALTHKIT_STEP_BOTH → View and save step counts in HUAWEI Health Kit.
HEALTHKIT_HEIGHTWEIGHT_BOTH → View and save height and weight in HUAWEI Health Kit.
HEALTHKIT_HEARTRATE_BOTH → View and save the heart rate data in HUAWEI Health Kit.
For details about the mapping between scopes and permissions, see Scope in the API reference.After successfully sign process , we can move to crud and other operations. We are able to call ten methods in DataController to perform operations on the fitness and health data.The methods include:
insert: inserts data.
delete: deletes data.
update: updates data.
read: reads data.
readTodaySummation: queries the summarized data of the current day.
readTodaySummationFromDevice: queries the summarized data of the local device of the current day.
registerModifyDataMonitor: registers a listener for data updates.
unregisterModifyDataMonitor: unregisters a listener for data updates.
syncAll: syncs data between the device and cloud.
clearAll: clears data of the app from the device and cloud.
We need to create the data controller object before starting operations.
Code:
val hiHealthOptions = HiHealthOptions.builder()
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_WRITE)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_WRITE)
.addDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT, HiHealthOptions.ACCESS_WRITE)
.build()
val signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions)
dataController = HuaweiHiHealth.getDataController(this, signInHuaweiId)
Inserting Data
We build a DataCollector object to insert body weight.
Code:
val dataCollector: DataCollector = DataCollector.Builder().setPackageName(this)
.setDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT)
.setDataStreamName("BODY_WEIGHT_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build()
We will create a sampling dataset based on the data collector.
Code:
val sampleSet = SampleSet.create(dataCollector)
We will create the start time, end time, and weight value for a DT_INSTANTANEOUS_BODY_WEIGHT sampling point.The weight value must be in float format.
Code:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())val currentDate = dateFormat.format(Date())val startDate: Date = dateFormat.parse(currentDate)val endDate: Date = dateFormat.parse(currentDate)val samplePoint = sampleSet.createSamplePoint().setTimeInterval(startDate.time, endDate.time, TimeUnit.MILLISECONDS)samplePoint.getFieldValue(Field.FIELD_BODY_WEIGHT).setFloatValue(weight)
sampleSet.addSample(samplePoint)
And in this time, we need to call the data controller to insert the sampling dataset into the Health platform.
Code:
val insertTask: Task = dataController.insert(sampleSet)
insertTask.addOnSuccessListener {
Log.i("HomeFragment","Success insert a SampleSet into HMS core")
showSampleData(sampleSet, "Insert Weight")
}.addOnFailureListener { e ->
Toast.makeText(this, e.message.toString(), Toast.LENGTH_LONG).show()
}
If you examine the showSampleData function, you can see how the added data was reached.
Code:
private fun showSampleData(sampleSet: SampleSet, desc: String) {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (samplePoint in sampleSet.samplePoints) {
Log.i("HomeFragment","Sample point type: " + samplePoint.dataType.name)
Log.i("HomeFragment", "Start: " + dateFormat.format(Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))))
Log.i("HomeFragment", "End: " + dateFormat.format(Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))))
for (field in samplePoint.dataType.fields) {
Log.i("HomeFragment", "Field: " + field.name + " Value: " + samplePoint.getFieldValue(field))
Toast.makeText(this, desc + samplePoint.getFieldValue(field), Toast.LENGTH_LONG).show()
}
}
}
Deleting Data
We will build a DataCollector object for data deletion.
Code:
val dataCollector: DataCollector = DataCollector.Builder().setPackageName(this)
.setDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT)
.setDataStreamName("BODY_WEIGHT_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build()
After creating data collector object, we need to build the time range for the deletion: start time and end time.
Code:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())
val startDate: Date = dateFormat.parse(startTimeEditText.text.toString())
val endDate: Date = dateFormat.parse(endTimeEditText.text.toString())
We build a parameter object as the conditions for the deletion while using DeleteOptions.So, the data in this time interval will be deleted.Also note that: Only historical data that has been inserted by the current app can be deleted from the Health platform.
Code:
val deleteOptions = DeleteOptions.Builder()
.addDataCollector(dataCollector)
.setTimeInterval(startDate.time, endDate.time, TimeUnit.MILLISECONDS)
.build()
And as last step, we use the specified condition deletion object to call the data controller to delete the sampling dataset.
Calling the data controller to delete the sampling dataset is an asynchronous operation. Therefore, a listener needs to be registered to monitor whether the data deletion is successful or not.
Code:
val deleteTask = dataController.delete(deleteOptions)
deleteTask.addOnSuccessListener {
Log.i("HomeFragment","Success delete steps data")
Toast.makeText([email protected], "Delete success", Toast.LENGTH_LONG).show()
}.addOnFailureListener {
Log.v(TAG, it.message.toString())
}
Updating Data
We will build a DataCollector object for data update.
This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/home
What is the difference between Huawei Health kit and Hihealth kit ?
Hello. Is there a way to correct data in the Huawei Health database?. For instance remove steps from a certain date?. Thank you!

Implementing Message Push for Your Quick App Rapidly

Now you have a quick app released on HUAWEI AppGallery. Do you want to attract more users and win more traffic for it? HUAWEI Push Kit can help you with that. You can push messages at the right moment to users for them to open your quick app to view more details. This better engages your users and improves activity.
Typical scenarios of push messages are as follows:
l Shopping quick apps can push information about new products and discounts to users to attract more customers for merchants.
l Reading quick apps can push information such as popular books and chapter updates to users, providing up-to-date information that users concern about.
l Food & drink quick apps can push information about food and good restaurants to users, facilitating user's life and bringing more users for the catering industry.
Follow instructions in this document to integrate HUAWEI Push Kit to your quick app to get all these benefits.
Getting Started
The hardware requirements are as follows:
l A computer with Node.js 10 or later and HUAWEI Quick App IDE of the latest version installed
l A Huawei mobile phone running EMUI 8.0 or later (with a USB cable)
Development Guide
Enabling HUAWEI Push Kit
1. Sign in to AppGallery Connect and click My projects.
2. Click the card of the project for which you need to enable the service. Click the Manage APIs tab, and toggle the Push Kit switch.
{
"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"
}
3. Click the General information tab. In the App information area, set SHA-256 certificate fingerprint to the SHA-256 fingerprint.
Subscribing to Push Messages
The service process is as follows.
1. Call the push.getProvider API to check whether the current device supports HUAWEI Push Kit. If huawei is returned, the device supports HUAWEI Push Kit. You can call other relevant APIs only when the device supports HUAWEI Push Kit.
2. Call the push.subscribe API to obtain regId (registered ID). The ID is also called a token or push token, which identifies messages sent by HUAWEI Push Kit.
Notice: It is recommended that the preceding APIs be called in app.ux that takes effect globally.
Code:
checkPushIsSupported(){
let provider= push.getProvider();
console.log("checkPush provider= "+provider);
if(provider==='huawei'){
this.pushsubscribe();
}
},
pushsubscribe() {
console.log("pushsubscribe start");
var that=this;
push.subscribe({
success: function (data) {
console.log("push.subscribe succeeded, result data=" + JSON.stringify(data));
that.dataApp.pushtoken=data.regId;
},
fail: function (data, code) {
console.log("push.subscribe failed, result data=" + JSON.stringify(data) + ", code=" + code);
},
complete: function () {
console.log("push.subscribe completed");
}
})
},
3. Report the obtained regId to the server of your quick app through the Fetch Data API, so the server can push messages to the device based on regId. Generally, the value of regId does not change and does not need to be reported to the server each time after it is obtained.
You are advised to call the Data Storage API to store the regId locally. Each time the regId is obtained, compare the regId with that stored locally. If they are the same, the regId does not need to be reported to the server. Otherwise, report the regId to the server.
The service process is as follows.
The sample code for comparing the obtained regId with that stored locally is as follows:
Code:
checkToken() {
var subscribeToken=this.$app.$def.dataApp.pushtoken;
console.log("checkToken subscribeToken= "+subscribeToken);
var storage = require("@system.storage");
var that=this;
storage.get({
key: 'token',
success: function (data) {
console.log("checkToken handling success data= "+data);
if (subscribeToken != data) {
// Report regId to your service server.
that.uploadToken(subscribeToken);
that.saveToken(subscribeToken);
}
},
fail: function (data, code) {
console.log("handling fail, code = " + code);
}
})
},
The sample code for saving regId locally is as follows:
Code:
saveToken(subscribeToken){
console.log("saveToken");
var storage = require("@system.storage");
storage.set({
key: 'token',
value: subscribeToken,
success: function (data) {
console.log("saveToken handling success");
},
fail: function (data, code) {
console.log("saveToken handling fail, code = " + code);
}
})
},
Testing Push Message Sending
You can test the push function by sending a push message to your test device. In this case, regId (push token) uniquely identifies your device. With it, your service server can accurately identify your device and push the message to your quick app on the device. Your device can receive the pushed message in any of the following conditions:
l The quick app has been added to the home screen.
l The quick app has been added to MY QUICK APP.
l The quick app has been used before.
l The quick app is running.
You can use either of the following methods to send a push message to a quick app that has been released on AppGallery or run by Huawei Quick App Loader.
l Select some target users in AppGallery Connect and send the push message.
l Call the specific server API to send the push message to users in batches.
Sending a Push Message Through AppGallery Connect
This method is simple. You only need to configure the recipients in AppGallery Connect. However, the target user scope is smaller than that through the API.
1. Sign in to AppGallery Connect and click My apps.
2. Find your app from the list and click the version that you want to test.
3. Go to Operate > Promotion > Push Kit. Click Add notification and configure the push message to be sent.
Sending a Push Message by Calling the API
1. Call the accessToken API to obtain the access token, which will be used in the push message sending API.
2. Call the push message sending API. The sample code of the push message body is as follows:
Code:
var mData = {
"pushtype": 0, // The value 0 indicates a notification message.
"pushbody": {
"title": "How can young people make a living? ",
"description": "Why did he choose to be a security guard after college graduation? ",
"page": "/", // Path of the quick app page that is displayed when a user taps a notification message. This parameter is valid only when pushtype is set to 0. /" Go to the app home page.
"params": {
"key1": "test1",
"key2": "test2"
},
"ringtone": {
"vibration": "true",
"breathLight": "true"
}
}
};
var formatJsonString = JSON.stringify(mData);
var messbody = {
"validate_only": false,
"message": {
"data": formatJsonString, // The data type is JsonString, not a JSON object.
"android": {
"fast_app_target": 1, // The value 1 indicates that a push message is sent to a quick app running by Huawei Quick App Loader. To send a push message to a quick app from AppGallery, set this parameter to 2.
"collapse_key": -1,
"delivery_priority": "HIGH",
"ttl": "1448s",
"bi_tag": "Trump",
},
"token": ['pushtoken1','pushtoken2'], // Target users of message pushing.
}
};
For details, please refer to Accessing HUAWEI Push Kit.
How much time it will take to integrate push kit into Quick App ?

How Can I Quickly Integrate Cloud Storage of AppGallery Connect into a nodeJS

HUAWEI AppGallery Connect Cloud Storage provides maintenance-free cloud storage functions.​Recently, the Cloud Storage Node.js SDK for server integration has been released. I’ve been using it for a while. You can also access the sample code on GitHub.
1. Configuring the Environment and Version Information​Version:cloudstorage-server”: “1.0.0”
Environment:Window-Node -v14.15.0,npm v6.14.8,Visual Studio Code
Test Device:PC
cloudstorage-server”: “1.0.0”
AppGallery Connect: https://developer.huawei.com/consumer/en/service/josp/agc/index.html
SDK version: agconnect/cloudstorage-server”: “1.0.0”
SDK integration command: npm install — save @agconnect/cloudstorage-server
2. Enabling and Configuring Cloud Storage in AppGallery Connect​Currently, Cloud Storage is still in beta testing. To use the service, you’ll first need to send an application by email. For details, visit the following address:
https://developer.huawei.com/consum...Gallery-connect-Guides/agc-cloudstorage-apply
Create an app first and add it to a project, or select an app from the project list on the My projects page in AppGallery Connect.
Under the project, go to Build > Cloud Storage, and click Enable now.
{
"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"
}
Configure a storage instance as required.
Define the security rules. In this example, the default rules are used.
Note: By default, only authorized users have read and write permissions.
3. Installing the Node.js Environment​I won’t be describing the detailed procedure for installing the Node.js environment, but here are a few tips:
1. You can download the Node.js package for Windows from this website: https://nodejs.org/en/download/.
2. When you install the environment, the related npm will be automatically installed. You can check its version number by running the following command.
3. I like to use Visual Studio Code (VS Code) for developing Node.js code. If you need to install one, here’s the website: http://code.visualstudio.com/
4. Once you’ve finished installing VS Code, open the testNodeJSDemo project, create a JavaScript file, and write some code.
5. Run the JavaScript file in VS Code. Go to RUN > Run and Debug. Select the Node.js file, and you can see the output at the bottom.
4. Integrating the SDK​1. Open the CLI, go to your project directory, and run the npm init command to create the package.json file. Keep pressing Enter to apply the default parameters.
2. Run the following command to add the Server SDK dependency of Cloud Storage to the file:
Code:
npm install --save @agconnect/cloudstorage-server
3. Download the authentication credential of the Server SDK from AppGallery Connect and save the credential to the path of the created project. If no credential is available, just create one.
5. Developing Functions​a) Perform the initialization.​You need to initialize both the Server SDK and the storage instance.
Code:
var { AGCClient, CredentialParser } = require("@agconnect/common-server");
var credential = CredentialParser.toCredential("./agc-apiclient-testnodejs.json");
AGCClient.initialize(credential);
const {StorageManagement} = require('@agconnect/cloudstorage-server');
b) Configure the storage instance.​Copy the bucket name of the project in AppGallery Connect and run the following code to initialize the bucket:
Code:
let bucketName = '9105385871708601205-ffeon'; // Configure the storage instance in AppGallery Connect.
c) Upload a file.​In this example, I upload the test123.txt file in the project path. You can use a file as required.
Code:
// uploadFile();
function uploadFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
bucket.upload('./test123.txt')
.then(res => console.log(res))
.catch(err => console.log(err));
}
d) Download a file.​Here, I download the test123.txt file from the root directory on the cloud and rename the downloaded file test_download.txt. This is just an example.
Code:
const fs = require('fs');
// downloadFile();
function downloadFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
const remoteFile = bucket.file('test123.txt');
const localFile = './test_download.txt';
remoteFile.createReadStream()
.on('error', err => {
})
.on('end', () => {
})
.pipe(fs.createWriteStream(localFile))
}
e) Delete a file.​Here, I delete the test123.txt file in the root directory from the cloud. This is also an example.
Code:
// deleteFile();
function deleteFile() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
const file = bucket.file('test123.txt');
file.delete().then(res => {
}).catch(err => {
})
}
f) List all files.​Here, I list all files in the root directory from the cloud.
Code:
//getFileList();
function getFileList() {
const storage = new StorageManagement();
const bucket = storage.bucket(bucketName);
bucket.getFiles({delimiter: '/'}).then(res => {
console.log(res)
}).catch(err => {
console.log(err);
})
}
6. Verifying Functions​1. Verify the upload function.​Delete the comment tag before uploadFile(); and run the node CloudStorage.js command to upload a file.
We can now see the uploaded test123.txt file in AppGallery Connect.
2. Verify the download function.​Delete the comment tag before downloadFile(); and run the node CloudStorage.js command to download a file. If you see no information, don’t worry, it’s normal.
You’ll then see the downloaded test_download.txt file in the following path.
3. Verify the function of listing files.​Delete the comment tag before getFileList(); and run the node CloudStorage.js command to view all files in the root directory. The following information is displayed.
You can see the same files displayed in AppGallery Connect.
4. Verify the deletion function.​Delete the comment tag before deleteFile(); and run the node CloudStorage.js command to delete a file. This function will also give back no output.
You can see that the test123.txt file in AppGallery Connect has been deleted as well.
7. Summary​Cloud Storage allows you to manage your project files using Node.js code without the hassle of building a server and O&M. Also, with AppGallery Connect, a web console, you can easily manage your files on the cloud.
In addition to file upload, download, and deletion, Cloud Storage also offers functions such as listing files and setting metadata.
Cloud Storage development guide:
https://developer.huawei.com/consum...-connect-Guides/agc-cloudstorage-introduction
Cloud Storage sample code:
https://github.com/AppGalleryConnec...ster/agc-cloudstorage-demo-nodejs/nodejs-demo
Is it free of cost?
Cloud Storage needs any prior permissions or approvals to use in app ?
Basavaraj.navi said:
Is it free of cost?
Click to expand...
Click to collapse
It has 10 GB of free storage per month, beyond which a fee will be charged. For more details, see this document.
shikkerimath said:
Cloud Storage needs any prior permissions or approvals to use in app ?
Click to expand...
Click to collapse
Cloud Storage is still in beta state. To use this service, send an email to [email protected] for application.After this, you can use it directly!

[Unity] HMS Push Kit full Integration and Troubleshooting

INTRODUCTION
In this article we will learn how to integrate the Push Kit into a Unity project from start to finish, constantly in groups and video game development communities questions and difficulties are triggered for developers so within this article I would like to touch on different problems that can be easily solved just by following a few steps and modifying certain values within the Unity editor.
{
"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"
}
MOST COMMON QUESTIONS IN DEV COMMUNITIES
Through the development communities, we have been presented with different questions that I have been collecting little by little, below I share some that are commonly repeated.
After importing the Evil Mind plugin, my project won't run on my device?
Add the Push Manager prefab and when I run the game in game mode it doesn't compile
How can I get the token that Push Kit returns to me when it is executed?
Unity cannot locate the Android SDK and I cannot run the project.
ARTICLE GOAL
Our goal in this article will be to be able to send a notification to our phone from App Gallery Connect using the token that HMS Push Kit gives us, we will achieve this by solving the problems that arise at the time of configuration.
STEPS
Configuration App Gallery Connect.
Configure Unity to run our project.
Import Evil Mind Plugin.
Configure our project with App Gallery Connect.
Create the class and the code to get the answer.
Obtain the log of our device
Add the token to App Gallery Connect
Try our game
APP GALLERY CONFIGURATION
As we know we must create a project in App Gallery Connect and add an app in order to configure the necessary data for our project. Let's start by logging into the AGC console to create a project.
Within the projects section we can create a new project where we must create an App which will be added to our project.
Once the application is created we must fill in the following data in the form, for this it will be necessary to create our project in Unity and assign the package name.
Let's go to unity to create the necessary data, Open unity and create a new project. Once the project is created, select Build Settings> Player Settings to assign your game data.
Remember to confirm that in Other Settings you also have your package correctly. Here we will answer one of the questions we have at the beginning of this article.
After importing the Evil Mind plugin, my project won't run on my device? This generally happens to us because we do not have the Backend value configured correctly and the minimum supported API, in the following image I share the data that you should place.
With this configuration we will be able to run our game on the device that we have connected, remember that if you are using a GMS device it will be necessary to install the HMS Core apk which you can download from this league. https://m.apkpure.com/es/hms-core/com.huawei.hwid/download once downloaded you can run huawei mobile services.
Running your project on the device should have a screen similar to this, we have not added the button yet but we will do it later, the important thing is that your scene compiles correctly.
UNITY CONFIGURATION
Let's start now with the configuration of our project in Unity. What we must do is import the Evil Mind plugin to be able to obtain the upper menu of Huawei and to be able to place the data obtained from AGC. Download the plugin from the repository that I share with you now. https://github.com/EvilMindDevs/hms-unity-plugin
Download the pcustom package to your computer and import it into Unity.
You must import it from the import tab and select custom package, once imported an option will be enabled in the upper menu with the title of Huawei, when you click on it you will get the following pop up.
Download the json file from AGC and replace it in Unity the path to find the json you can find in the following image
Open the agconnect file and start putting the necessary data to paste into the Huawei plugin. In the image I am showing you in yellow what data you must take to place them in the plugin window.
When you finish assigning the data, click on the Configure Manifest button. IMPORTANT JUST GIVE A CLICK, OTHERWISE YOU WILL ADD LINES TO YOUR MANIFEST AND THE ERROR WILL BE PRESENTED Merge Manifest.
Check your android Manifest take into account that when you import the plugin, a default Manifest will be downloaded in your project, that Manifest Default has packages that belong to the example, so it is important that you only have the following <providers> as I show in the image
Add the Push Manager prefab to your scene, you can also add a button inside a Canvas to initialize the Push Kit service, leave it in the onStart () method;
  
Run your project again to identify errors if they occur during the compilation and construction of the project. This will not generate any effect in Push Kit nor will it grant you the token because we have not configured the SHA256 signature, possibly the console will indicate that the fingerprint has not been configured. We are going to configure this signature. Create your keystore in your project folder, go to the folder where your project is with your console and execute the following command.
Replace the name of your keystore
keytool -list -v -keystore d:key.keystore
Get the Sha 256 and place it in AGC.
CODING
We will create a script that is responsible for initializing the service and granting us the token of our device and then sending the notification through token.
Java:
namespace HmsPlugin
{
public class PushKitManager : MonoBehaviour, IPushListener
{
public Action<string> OnTokenSuccess { get; set; }
public Action<Exception> OnTokenFailure { get; set; }
public Action<RemoteMessage> OnMessageReceivedSuccess { get; set; }
// Start is called before the first frame update
void Start()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"[HMS] Push token from GetToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnNewToken(string token)
{
Debug.Log($"[HMS] Push token from OnNewToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnTokenError(Exception e)
{
Debug.Log("Error asking for Push token");
Debug.Log(e.StackTrace);
OnTokenFailure?.Invoke(e);
}
public void OnMessageReceived(RemoteMessage remoteMessage)
{
OnMessageReceivedSuccess?.Invoke(remoteMessage);
}
}
}
We will also create a method only as an example to be able to initialize the service and obtain the token
Java:
public void StartNotificationService()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"The token {token}");
if(token != null)
{
}OnTokenSuccess?.Invoke(token);
}
Now we need to obtain the token of our phone and that the Log will return us and we will place it in the push notification service.
Fill in the necessary data to send the notification such as the Title, the Body and the name of the notification. You must also configure the device parameters. In this section is where you must add the token obtained from your device.
Now just launch the notification
TIPS AND TRICKS
I dont know how to obtain logs from my Android Device. In the following steps you'll learn how to debug from your Device.
For troubleshooting and debugging, it is often very helpful to capture the device logs. The device logs contain information about the status of a running application on the device and any errors encountered. The IAP Engineering team requires logs for open issues. It is assumed here that you have an Android device configured with Developer options and attached to a PC with a USB cable. These steps show the process on a Windows system and works similarly on a Mac
1. In Unity, find the location of the Android SDK. From the Edit menu, choose Preferences/External Tools
2. Look for the Android SDK. On my system it was C:\Users\[username]\AppData\Local\Android\sdk
3. Open a command prompt, and change to this directory.
4. Change directory to the platform-tools subdirectory.
5. You should see adb.exe in this directory.
6. With the device connected via USB, run the following command:
adb devices (Mac is ./adb devices)
7. This should return device serial number followed by the word "device"
8. Run "adb logcat | findstr -i unity" (use grep on Mac) in the terminal window. This will find anything with the word "unity" in the output, case insensitive.
9. This will provide the contents of the device log that are associated with a running Unity application
The output can be quite verbose. You can browse through the log however, looking for such words as "error" and "exception". Sometimes customer support will ask for device logs, in which case you can send the output to a text file with the command "adb logcat -d | findstr -i unity > log.txt"
CONCLUSION
Push notifications are one of the trending tools in marketing arenas. No arena has been left untouched by the tool- after engaging users brilliantly on an e-commerce store, it’s the turn of the gaming app push notifications.
Mobile gaming apps have gone too far popular in today’s arena so much so that mobiles have been developed specifically for the game, consisting of the hardware that would meet the demands of the users.In this article we learned how to implement HMS Kit Push notification in oour Unity Game an it was very fast.
REFERENCES
Push Kit - Cloud Message Push- Cross-Platform Messaging Solution - HUAWEI Developer
Push Kit can satisfy the relevance and freshness of content update that your users want. Push instant messages from the cloud to user devices.
developer.huawei.com
Read In Forum
SPANISH VIDEOTUTORIAL
If you speak or understand spanish here you have the videotutorial.

Categories

Resources