Track Fitness Application using Huawei Health Kit - Huawei Developers

Overview
Track Fitness application provides users daily step count, calorie burn, how much time user is doing exercise and total distance travelled during that time. Using these real time information, user can keep his fitness record on daily basis and can set a goal towards his fitness. This application uses the Room database for saving the records and displaying in the list. This application uses Huawei Account Kit and Health Kit for login and getting his real time step count. Let us know little about Huawei Health Kit, then we will focus on the implementation part.
Huawei Health Kit
HUAWEI Health Kit provides services for user’s health and fitness data. Using this kit, developers can get real time Step Count, Heart Rate, Body Temperature etc.
Huawei Health Kit provides the following key APIs for the Android client
1) Data Controller: Developers can use this API to insert, delete, update, and read data, as well as listen to data updates by registering a listener.
2) Activity Records Controller: Developers can use this API for tracking daily activity for users like Running, Sleeping etc.
3) Auto Recorder Controller: Developers can use this API to read sensor data in real time like step count.
Integration Started
1) First create an app in AppGallery Connect (AGC).
2) Get the SHA Key. For getting the SHA key, refer this article.
3) Click on Health kit in console.
{
"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"
}
4) Click Apply for Health Kit.
5) Select Product Type as Mobile App, APK Name as your project package name and check the required permission for your application to work, as shown below:
Finally click Submit button to apply for health kit.
6) Check if status is Enabled, as shown in below image.
7) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below Health Kit, account kit and auth service dependencies in the dependencies section:
Code:
implementation 'com.huawei.hms:base:4.0.0.100'
implementation 'com.huawei.hms:hwid:4.0.0.300'
implementation 'com.huawei.hms:health:5.0.3.300'
10) Enter the dependencies for saving data in Room database.
Code:
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
11) Add the app ID generated when the creating the app on HUAWEI Developers to manifest file.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="Your app id"/>
12) Add the below permissions to manifest file.
Code:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.BODY_SENSORS" />
13) Sync the gradle. Now configuration part completed.
Let us start with the coding part which will explain how to sign in with Huawei id, get authorization access for Health Kit and generate real time step data.
Step 1: Initialize the health service.
Inside activity onCreate() method, call initService().
Code:
private void initService() {
mContext = this;
HiHealthOptions fitnessOptions = HiHealthOptions.builder().build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(fitnessOptions);
mSettingController = HuaweiHiHealth.getSettingController(mContext, signInHuaweiId);
}
Step 2: Huawei Id SignIn and Apply for permissions.
Code:
/**
* Sign-in and authorization method. The authorization screen will display if the current account has not granted authorization.
*/
private void signIn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example. You need to add scopes according to your specific needs.
scopeList.add(new Scope(Scopes.HEALTHKIT_STEP_BOTH)); // View and save step counts in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEIGHTWEIGHT_BOTH)); // View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_HEARTRATE_BOTH)); // View and save the heart rate data in HUAWEI Health Kit.
// Configure authorization parameters.
HuaweiIdAuthParamsHelper authParamsHelper = new HuaweiIdAuthParamsHelper(
HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
HuaweiIdAuthParams authParams = authParamsHelper.setIdToken()
.setAccessToken()
.setScopeList(scopeList)
.createParams();
// Initialize the HuaweiIdAuthService object.
final HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(this.getApplicationContext(),
authParams);
// Silent sign-in. If authorization has been granted by the current account, the authorization screen will not display. This is an asynchronous method.
Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();
// Add the callback for the call result.
authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId huaweiId) {
// The silent sign-in is successful.
Log.i(TAG, "silentSignIn success");
Toast.makeText(GetStartedActivity.this, "silentSignIn success", Toast.LENGTH_SHORT).show();
goToHomeScreen();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
// The silent sign-in fails. This indicates that the authorization has not been granted by the current account.
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
Log.i(TAG, "begin sign in by intent");
// Call the sign-in API using the getSignInIntent() method.
Intent signInIntent = authService.getSignInIntent();
// Display the authorization screen by using the startActivityForResult() method of the activity.
// You can change HihealthKitMainActivity to the actual activity.
GetStartedActivity.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0203428726840520025

Related

HUAWEI Game Service Implementation : Events

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Game service provides a centralized place for you to manage game services and configure metadata for authorizing and authenticating your game. Using Huawei game service, developer can access range of capabilities to help develop your games more efficiently.
Features
1. Developers can promote their game efficiently and quickly.
2. Developers can easily build the foundation of game by implementing features like achievements and events.
3. Developers can perform in-depth operations tailored to their game and their users.
In this article, we will implement event feature provided by Huawei game service in Tic tac toe game.
{
"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"
}
Prerequisites
1. Developer has created an application on App Gallery Connect. Follow Creating an App.
2. Integrating app gallery connect SDK. Please refer to AppGallery Connect Service Getting Started.
3. Developer has integrated Huawei Account kit. Follow this tutorial to integrate account kit.
4. HUAWEI mobile phone with HMS Core 4.0.0.300 or later installed.
Setup:
1. Enable Huawei Game service in Manage APIS. Please refer to Service Enabling.
2. Add appgallery connect plug-in in app-level build.gradle
Code:
apply plugin: 'com.huawei.agconnect'
3. Add following dependencies in app-level build.gradle and click on Sync Now and wait till synchronization is done.
Code:
dependencies {
implementation 'com.huawei.hms:base:4.0.4.301'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:iap:4.0.4.300'
implementation 'com.huawei.hms:game:4.0.3.301'
}
Initialization
Once Initial set up is done, let’s implement Huawei game service in Tic tac toe game
1. Add the following code in onCreate() method of Application class.
Code:
public class GameServiceApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
HuaweiMobileServicesUtil.setApplication(this);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
2. To initialize the game
Code:
private void init() {
JosAppsClient appsClient = JosApps.getJosAppsClient(this, null);
appsClient.init();
Log.i(TAG, "initialization success");
}
Signin In
1. When app is launched, Huawei sign-in page is displayed.
2. User enters Huawei Huawei ID and password to sign in.
3. After a successful sign in, the app obtains player information corresponding to Huawei ID.
Please refer to this article for sign in implementation.
Game Events
The Game events allow developer to collect specific data generated by players and store them on Huawei game server for AppGallery connect. In this article, we will collect data pertaining to player win. Every time players win the match, we will store it in Huawei game server.
Creating an Event in AppGallery Connect
1. Sign in to AppGallery Connect and select My apps.
2. Select an app from the app list to create an event.
3. Click the Operate tab and go to Products > Game Event. Click Create.
4. Configure the event information and click Save.
5. Check your event ID on the event list and properly save the ID for event development.
Implementation of Event
1. To initialize EventsClient instance
Code:
EventsClient client = Games.getEventsClient(this, mAuthHuaweiId);
mAuthHuaweiId is obtained during sign in.
2. To submit the event
Code:
client.grow(eventId, growAmount);
eventId indicates the ID of the event which is generated while defining the event in AppGallery connect. In our app we will submit the event everytime players win the match.
The growAmount parameter specifies an increment amount of the event value.
To Obtain Events
Following code can be used to obtain the events.
Code:
Task<List<Event>> task = client.getEventList(forceReload);
forceReload is a Boolean type used to indicate whether to obtain data stored on the Huawei game server or locally cached data.
Following code shows how list of events are returned.
Code:
task.addOnSuccessListener(new OnSuccessListener<List<Event>>() {
@Override
public void onSuccess(List<Event> data) {
if (data == null) {
Log.w("Event", "event is null");
return;
}
for (Event event : data) {
Log.i("Event", "event id:" + event.getEventId());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
if (e instanceof ApiException) {
String result = "errorCode:"
+ ((ApiException) e).getStatusCode();
Log.e("Event", result);
}
}
});
We will show the retrieved events list in recyclerview. Clicking on event list item will show details about the events.
Code:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Event event = eventList.get(position);
final String eventId = event.getEventId();
Glide.with(context).load(event.getThumbnailUri()).into(holder.eventImage);
holder.eventName.setText(event.getName());
holder.eventAmonut.setText("value:"+event.getValue() + "#" + event.getLocaleValue());
holder.eventDes.setText(event.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.onItemClick(position);
}
});
holder.eventReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.reportEvent(eventId);
}
});
}
Screenshots
​ Summary
In this article, we understood initial setup and game event features of Huawei Game Service. In next article, we will discuss more features provided by Huawei Game service.
Source code can be downloaded from https://github.com/DTSE-India-Community/Huawei-Game-Service
How many days it will take to get data reflected in AGC.

Online Food ordering app ([email protected]) using AGC Auth Service | JAVA

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Online food ordering is process that delivers food from local restaurants. Mobile apps make our world better and easier customer to prefer comfort and quality instead of quantity.
Sign In Module
User can login with mobile number to access food order application. Using auth service we can integrate third party sign in options. Huawei Auth service provides a cloud based auth service and SDK.
In this article, following Kits are covered:
1. AGC Auth Service
2. Ads Kit
3. Site kit
Steps
1. Create App in Android.
2. Configure App in AGC.
3. Integrate the SDK in our new Android project.
4. Integrate the dependencies.
5. Sync project.
Screens
{
"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"
}
Configuration
1. Login into AppGallery Connect, select FoodApp in My Project list.
2. Enable required APIs in manage APIs tab.
Choose Project Settings > ManageAPIs
3. Enable auth service before enabling Authentication modes as we need to enable Auth Service.
  Choose Build > Auth Service and click Enable now top right-corner
4. Enable sign in modes required for application
Integration
Create Application in Android Studio.
App level gradle dependencies.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Gradle dependencies
Code:
implementation 'com.google.android.material:material:1.3.0-alpha02'
implementation 'com.huawei.agconnect:agconnect-core:1.4.0.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.0.300'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:site:4.0.3.300'
implementation 'com.huawei.hms:ads-lite:13.4.30.307'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
Add the below permissions in Android Manifest file
Code:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ...
</manifest>
Ads Kit: Huawei ads SDK to quickly integrate ads into your app, ads can be a powerful assistant to attract users.
Code Snippet
Code:
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/huawei_banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
hwads:adId="testw6vs28auh3"
hwads:bannerSize="BANNER_SIZE_360_57" />
Code:
BannerView hwBannerView = findViewById(R.id.huawei_banner_view);
AdParam adParam = new AdParam.Builder()
.build();
hwBannerView.loadAd(adParam);
Auth Service:
1. Create Object for VerifyCodeSettings. Apply for verification code by mobile number based login.
Code:
VerifyCodeSettings mVerifyCodeSettings = VerifyCodeSettings.newBuilder()
.action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
.sendInterval(30)
.locale(Locale.getDefault())
.build();
2. Send mobile number, country code and verify code settings object.
Code:
if (!mMobileNumber.isEmpty() && mMobileNumber.length() == 10) {
Task<VerifyCodeResult> resultTask = PhoneAuthProvider.requestVerifyCode("+91", mMobileNumber, mVerifyCodeSettings);
resultTask.addOnSuccessListener(verifyCodeResult -> {
Toast.makeText(SignIn.this, "verify code has been sent.", Toast.LENGTH_SHORT).show();
if (!isDialogShown) {
verfiyOtp();
}
}).addOnFailureListener(e -> Toast.makeText(SignIn.this, "Send verify code failed.", Toast.LENGTH_SHORT).show());
Toast.makeText(this, mEdtPhone.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Invalid Phone Number!", Toast.LENGTH_SHORT).show();
}
3. Create object for Phone User Builder.
Code:
PhoneUser mPhoneUser = new PhoneUser.Builder()
.setCountryCode("+91")
.setPhoneNumber(mMobileNumber)
.setVerifyCode(otp)
.setPassword(null)
.build();
4. Check below code snippet to validate OTP.
Code:
AGConnectAuth.getInstance().createUser(mPhoneUser)
.addOnSuccessListener(signInResult -> {
Toast.makeText(SignIn.this, "Verfication success!", Toast.LENGTH_LONG).show();
SharedPrefenceHelper.setPreferencesBoolean(SignIn.this, IS_LOGGEDIN, true);
redirectActivity(MainActivity.class);
}).addOnFailureListener(e -> Toast.makeText(SignIn.this, "Verfication failed!", Toast.LENGTH_LONG).show());
Site kit: Using HMS Site kit we can provide easy access to hotels and places.
Code:
searchService.textSearch(textSearchRequest, new SearchResultListener<TextSearchResponse>() {
@Override
public void onSearchResult(TextSearchResponse response) {
for (Site site : response.getSites()) {
SearchResult searchResult = new SearchResult(site.getAddress().getLocality(), site.getName());
String result = site.getName() + "," + site.getAddress().getSubAdminArea() + "\n" +
site.getAddress().getAdminArea() + "," +
site.getAddress().getLocality() + "\n" +
site.getAddress().getCountry() + "\n";
list.add(result);
searchList.add(searchResult);
}
mAutoCompleteAdapter.clear();
mAutoCompleteAdapter.addAll(list);
mAutoCompleteAdapter.notifyDataSetChanged();
autoCompleteTextView.setAdapter(mAutoCompleteAdapter);
Toast.makeText(getActivity(), String.valueOf(response.getTotalCount()), Toast.LENGTH_SHORT).show();
}
@Override
public void onSearchError(SearchStatus searchStatus) {
Toast.makeText(getActivity(), searchStatus.getErrorCode(), Toast.LENGTH_SHORT).show();
}
});
Result:
Conclusion:
In this article we have learnt Auth service,Ads Kit & site kit Integration in food application.
Reference:
Auth Service:
https://developer.huawei.com/consumer/en/doc/development/Tools-Guides/agc-conversion-auth-0000001050157270
Ads Kit :
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-introduction-0000001050064960
Site Kit :
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-introduction-0000001050158571

Exploring the Huawei Health Kit: Sensors Controller

More information like this, you can visit HUAWEI Developer Forum​
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 HiHealth Kit 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.
HiHealth:
https://developer.huawei.com/consumer/en/hms/huawei-healthkit
HealthKit:
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 Sensors 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.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" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
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 Sensors Controller functionalities in our project.
Sensors Controller
We can achieve success in the two different scenarios with the sensor controller.The first of these scenarios is to be able to access the built-in sensor that the phone contains like pedometer.You can directly call the register method of SensorsController to register a listener to obtain the data reported by the built-in sensor.
NOTE : Currently, Health Kit does not support the access of devices. If you request the access of fitness and health devices to help users collect data, use HiHealth Kit (for the integration of the HUAWEI Health app) instead.
HiHealth Kit is also applicable if you would like to obtain the fitness and health data collected by Huawei wearables or Huawei ecosystem partners for your services offered to customers.
Using the Built-in Sensor Data of the Phone
Let’s give an example about that how to obtain the incremental step count from a phone.
Firstly, we need to sign in to your HUAWEI ID and obtain the SensorsController object.
Code:
val options = HiHealthOptions.builder().build()
// Sign in to the HUAWEI ID.
val signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(options)
// Obtain the SensorsController
sensorsController = HuaweiHiHealth.getSensorsController(this, signInHuaweiId)
After that, we will register a listener to listen to the step count.To register a listener for receiving raw data reported by a specified data collector, use the SensorsController.register method.
Code:
private val onSamplePointListener =
OnSamplePointListener { samplePoint ->
showSamplePoint(samplePoint)
}
val builder = SensorOptions.Builder()
builder.setDataType(DataType.DT_CONTINUOUS_STEPS_TOTAL)
sensorsController!!.register(builder.build(), onSamplePointListener)
.addOnSuccessListener {
Toast.makeText(this, "registerSteps successed... ", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Toast.makeText(this, "registerSteps failed... ", Toast.LENGTH_SHORT).show()
}
When we no longer need step data, we can use the SensorsController.unregister method to unregister the listener.
Code:
sensorsController!!.unregister(onSamplePointListener).addOnSuccessListener {
Toast.makeText(this, "unregisterSteps successed ...", Toast.LENGTH_SHORT).show()
}.addOnFailureListener { e ->
Toast.makeText(this, "unregisterSteps failed ...", Toast.LENGTH_SHORT).show()
}
Using an External Bluetooth Device
In the second scenario, we will examine how data can be obtained from external bluetooth devices.Note that : Health Kit currently supports only standard Bluetooth BLE heart rate device.
Currently, Health Kit does not support reading data generated by Huawei wearables and the HUAWEI Health app. It is scheduled that the HUAWEI Health app data, including step count, sleep data, workout records, heart rate, and body fat, will be opened up in the future.
Let’s give an example about that how to obtain the heart rate data from the Bluetooth device.
Firstly, we need to sign in to your HUAWEI ID and obtain the BleController and SensorsController objects.
Code:
val options = HiHealthOptions.builder().build()
val signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(options)
sensorsController = HuaweiHiHealth.getSensorsController(this, signInHuaweiId)
bleController = HuaweiHiHealth.getBleController(this, signInHuaweiId)
After that, we need to create a bluetooth scanning callback object by using BleScanCallback.BLE devices detected during the scanning will automatically be called back to the bleDeviceInfo object.
Code:
private val mBleCallback: BleScanCallback = object : BleScanCallback() {
override fun onDeviceDiscover(bleDeviceInfo: BleDeviceInfo) {
// Bluetooth devices detected during the scanning will be called back to the bleDeviceInfo object
Toast.makeText([email protected], "onDeviceDiscover : " + bleDeviceInfo.deviceName, Toast.LENGTH_SHORT).show()
// Save the scanned heart rate devices to the variables for later use.
[email protected] = bleDeviceInfo
}
override fun onScanEnd() {
Toast.makeText([email protected], "onScanEnd Scan called", Toast.LENGTH_SHORT).show()
}
}
For now, we can start scan for available BLE devices.We need to use the BleController.beginScan method to scan for nearby BLE devices.
Code:
bleController!!.beginScan(listOf(DataType.DT_INSTANTANEOUS_HEART_RATE), 15, mBleCallback)
We can stop scanning for Bluetooth devices.We need to use the BleController.endScan method to stop scanning.
Code:
bleController!!.endScan(mBleCallback)
We can save the device to be used by SensorsController.We need to use the BleController.saveDevice method to save the device.After successfully saving the device, you can obtain the data collector objects of the device via SensorsController, for example, using the SensorsController.getDataCollectors method.
Code:
bleController!!.saveDevice(bleDeviceInfo).addOnSuccessListener {
Toast.makeText(this, "saveHeartRateDevice successed... ", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this, "saveHeartRateDevice failed... ", Toast.LENGTH_SHORT).show()
}
We can delete a device if a BLE device is no longer used.We need to use the BleController.deleteDevice method to delete it.
Code:
bleController!!.deleteDevice(bleDeviceInfo).addOnSuccessListener {
Toast.makeText(this, "removeHeartRateDevice successed... ", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this, "removeHeartRateDevice failed... ", Toast.LENGTH_SHORT).show()
}
We can also list all external BLE devices that have been saved.
Code:
val bleDeviceInfoTask = bleController!!.savedDevices
bleDeviceInfoTask.addOnSuccessListener { bleDeviceInfos -> // bleDeviceInfos contains the list of the saved devices.
for (bleDeviceInfo in bleDeviceInfos) {
Toast.makeText(this, "Matched BLE devices:" + bleDeviceInfo.deviceName, Toast.LENGTH_SHORT).show()
}
}
We can obtain data collectors of the device.We need to use the SensorsController.getDataCollectors method to obtain all saved data collectors.
Code:
val dataCollectorsOptions = DataCollectorsOptions.Builder().setDataTypes(DataType.DT_INSTANTANEOUS_HEART_RATE).build()
sensorsController!!.getDataCollectors(dataCollectorsOptions)
.addOnSuccessListener { dataCollectors ->
// dataCollectors contains the returned available data collectors.
for (dataCollector in dataCollectors) {
Toast.makeText(this, "Available data collector:" + dataCollector.dataCollectorName, Toast.LENGTH_SHORT).show()
// Save the heart rate data collectors for later use when registering the listener.
[email protected] = dataCollector
}
}
.addOnFailureListener {
Toast.makeText(this, "findDataCollectors failed... ", Toast.LENGTH_SHORT).show()
}
We must use the SensorsController.register method to register a listener for receiving raw data reported by a specified data collector.We will create a listener object for heart rate data. The received heart rate data will be called back to onSamplePoint.
Code:
sensorsController!!.register(
SensorOptions.Builder()
.setDataType(DataType.DT_INSTANTANEOUS_HEART_RATE)
.setDataCollector(dataCollector)
.setCollectionRate(1, TimeUnit.SECONDS)
.build(),
heartrateListener
).addOnSuccessListener(OnSuccessListener<Void?> {
Toast.makeText(this, "registerHeartRate successed... ", Toast.LENGTH_SHORT).show()
}).addOnFailureListener(OnFailureListener {
Toast.makeText(this, "registerHeartRate failed... ", Toast.LENGTH_SHORT).show()
})
private val heartrateListener = OnSamplePointListener { samplePoint ->
Toast.makeText(this, "Heart rate received " + samplePoint.getFieldValue(Field.FIELD_BPM), Toast.LENGTH_SHORT).show()
}
If we do not need to receive real-time data, we can unregister a listener.We need to use the SensorsController.unregister method to unregister the listener.
Code:
sensorsController!!.unregister(heartrateListener).addOnSuccessListener {
Toast.makeText(this, "unregisterHeartRate successed... ", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this, "unregisterHeartRate failed... ", Toast.LENGTH_SHORT).show()
}
References:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/service-introduction-0000001050071661
https://forums.developer.huawei.com/forumPortal/en/home
Well explained, can we connect to Non-Huawei devices?

Implement the Automatic Bill Number Input Function Using ML Kit’s Text Recognition

More information like this, you can visit HUAWEI Developer Forum​
Introduction
In the previous post, we looked at how to use HUAWEI ML Kit’s card recognition function to implement the card binding function. With this function, users only need to provide a photo of their card, and your app will automatically recognize all of the key information. That makes entering card information much easier, but can we do the same thing for bills or discount coupons? Of course we can! In this post, I will show you how to implement automatic input of bill numbers and discount codes using HUAWEI ML Kit’s text recognition function.
Application
Text recognition is useful in a huge range of situations. For example, if you scan the following bill, indicate that the bill service number starts with “NO.DE SERVICIO”, and limit the length to 12 characters, you can quickly get the bill service number “123456789123” using the text recognition.
{
"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"
}
Similarly, if you scan the discount coupon below, start the discount code with “FAVE-” and limit the length to 4 characters, you’ll get the discount code “8329”, and can then complete the payment.
Pretty useful, right? You can also customize the information you want your app to recognize.
Integrating Text Recognition
So, let’s look at how to process bill numbers and discount codes.
1. Preparations
You can find detailed information about the preparations you need to make on the HUAWEI Developer.
Here, we’ll just look at the most important procedures.
1.1 Configure the Maven Repository Address in the Project-Level build.gradle File
Code:
buildscript {
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
}
dependencies {
...
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
allprojects {
repositories {
...
maven {url 'https://developer.huawei.com/repo/'}
}
}
1.2 Add Configurations to the File Header
Once you’ve integrated the SDK, add the following configuration to the file header:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
1.3 Configure SDK Dependencies in the App-Level build.gradle File
Code:
dependencies {
// Import the base SDK.
implementation 'com.huawei.hms:ml-computer-vision-ocr:2.0.1.300'
// Import the Latin character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-latin-model:2.0.1.300'
// Import the Japanese and Korean character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-jk-model:2.0.1.300'
// Import the Chinese and English character recognition model package.
implementation 'com.huawei.hms:ml-computer-vision-ocr-cn-model:2.0.1.300'
}
1.4 Add these Statements to the AndroidManifest.xml File so the Machine Learning Model can Automatically Update
Code:
<manifest>
...
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value="ocr" />
...
</manifest>
1.5 Apply for the Camera Permission
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
2. Code Development
2.1 Create an Analyzer
Code:
MLTextAnalyzer analyzer = new MLTextAnalyzer.Factory(context).setLanguage(type).create();
2.2 Set the Recognition Result Processor to Bind with the Analyzer
Code:
analyzer.setTransactor(new OcrDetectorProcessor());
2.3 Call the Synchronous API
Use the built-in LensEngine of the SDK to create an object, register the analyzer, and initialize camera parameters.
Code:
lensEngine = new LensEngine.Creator(context, analyzer)
.setLensType(LensEngine.BACK_LENS)
.applyDisplayDimension(width, height)
.applyFps(30.0f)
.enableAutomaticFocus(true)
.create();
2.4 Call the run Method to Start the Camera and Read the Camera Streams for the Recognition
Code:
try {
lensEngine.run(holder);
} catch (IOException e) {
// Exception handling logic.
Log.e("TAG", "e=" + e.getMessage());
}
2.5 Process the Recognition Result As Required
Code:
public class OcrDetectorProcessor implements MLAnalyzer.MLTransactor<MLText.Block> {
@Override
public void transactResult(MLAnalyzer.Result<MLText.Block> results) {
SparseArray<MLText.Block> items = results.getAnalyseList();
// Process the recognition result as required. Only the detection results are processed.
// Other detection-related APIs provided by ML Kit cannot be called.
…
}
@Override
public void destroy() {
// Callback method used to release resources when the detection ends.
}
}
2.6 Stop the Analyzer and Release the Detection Resources When the Detection Ends
Code:
if (analyzer != null) {
try {
analyzer.stop();
} catch (IOException e) {
// Exception handling.
}
}
if (lensEngine != null) {
lensEngine.release();
}
Demo Effect
And that’s it! Remember that you can expand this capability if you need to. Now, let’s look at how to scan travel bills.
And here’s how to scan discount codes to quickly obtain online discounts and complete payments.
Github Source Code
https://github.com/HMS-Core/hms-ml-demo/tree/master/Receipt-Text-Recognition
Awsome work !!

Integration of Huawei Account Kit and Analytics Kit in Android App KnowMyBoard Part -1

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will learn how to integrate the Huawei Account kit and Analytics kit in KnowMyBoard application. This is the first part of the application where, we are using Huawei Account kit for user login and Analytics kit for analysis and custom events for application usage and behaviour. You may expect second part soon, where we are using Huawei Location kit and ML kit.
Huawei Account kit provides simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts details and wait for authorization. user can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their Huawei IDs.
Supported Devices
Huawei Analytics kit is a one-stop user behaviour analysis platform for products such as mobile apps, web apps, quick apps, quick games, and mini-programs. It offers scenario-specific data collection, management, analysis, and usage, helping enterprises achieve effective user acquisition, product optimization, precise operations, and business growth.
It is a one-stop digital, intelligent data analysis platform tailored to meet the needs of enterprises cross-departmental and cross-role personnel.
Supported Devices
Development Overview
You need to install Android Studio IDE and I assume that you have prior knowledge about the Android application development in java.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
Android phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software
HMS Core (APK) 4.X or later.
Integration process
Step 1: Create android project.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
[/B][/B]
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.hms:hwid:6.4.0.301'
implementation 'com.huawei.hms:hianalytics:6.4.1.302'
[B][B]
Root level gradle dependencies
[/B][/B][/B]
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
[B][B][B]
Step 3: Add the below permissions in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Create project and configure app in AppGallery.
Step 5: Download and add agconnect-services.json file in app directory of project.
Let's start coding
MainActivity.java
[/B]
public class MainActivity extends AppCompatActivity {
LoginViewModel loginViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.setActivity(this);
// Enable SDK log recording.
HiAnalyticsTools.enableLog();
MyApplication.getAnalyticsInstance().setUserProfile("UserName","Test123");
loginViewModel = new LoginViewModel(getApplication());
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLoginViewModel(loginViewModel);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
AuthAccount authAccount = authAccountTask.getResult();
UserData userData = new UserData();
userData.setAccessToken(authAccount.getAccessToken());
userData.setCountryCode(authAccount.getCountryCode());
userData.setDisplayName(authAccount.getDisplayName());
userData.setEmail(authAccount.getEmail());
userData.setFamilyName(authAccount.getFamilyName());
userData.setGivenName(authAccount.getGivenName());
userData.setIdToken(authAccount.getIdToken());
userData.setOpenId(authAccount.getOpenId());
userData.setUid(authAccount.getUid());
userData.setPhotoUriString(authAccount.getAvatarUriString());
userData.setUnionId(authAccount.getUnionId());
updateMessage("Welcome " + userData.getDisplayName());
} else {
// The sign-in failed.
Log.e("TAG", "sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
updateMessage(getResources().getString(R.string.msg_signin_failed));
}
}
}
public void updateMessage(String msg) {
binding.txtMessage.setText(msg);
}
}
[B]
LoginViewModel.java
[/B][/B]
public class LoginViewModel extends AndroidViewModel {
private MyApplication app;
AccountAuthService service;
public String message = "Login required";
public LoginViewModel(@NonNull Application application) {
super(application);
app = (MyApplication) application;
}
public void loginClicked() {
AccountAuthParams authParams = new
AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
service = AccountAuthManager.getService(MyApplication.getActivity(), authParams);
MyApplication.getActivity().startActivityForResult(service.getSignInIntent(), 8888);
}
}
[B][B]
Result
Tricks and Tips
Makes sure that agconnect-services.json file added.
Make sure required dependencies are added
Make sure that service is enabled in AGC
Makes sure Analytics service is enable in AGC
Conclusion
In this article, we have learnt how to integrate Huawei Account kit, and Analytics kit Android application KnowMyBoard part-1. Account kit helps users to login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission. Analytics kit helps in app analysis and user behaviour.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit and Analytics kit in Android application KnowMyBoard.
Reference
Account Kit- Training Video
Analytics Kit- Training Video
Checkout in forum

Categories

Resources