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?
Related
More articles like this, you can visit HUAWEI Developer Forum
Want to retrieve health or fitness data of users based on their HUAWEI ID and show in your app?
{
"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"
}
Health Kit provide main three feature:
Data storage
Provides a data platform for developers to store fitness and health data.
Data openness
Provides a wide range of fitness and health APIs and supports sharing of the various fitness and health data, including step count, weight, and heart rate.
Data access authorization management
Provides settings for users and developers so users can manage developer's access to their health and fitness data, guaranteeing users' data privacy and legal rights.
Developement
1.Register HUAWEI ID and apply for Account Service*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-id-0000001050069756
2. Applying for Health Kit in developer console*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-kitservice-0000001050071707
3. Integrate HMS Health Kit
In Build.gradle file,add the implementation.
Code:
implementation 'com.huawei.hms:hihealth-base:{5.0.0.300}
In AndroidManifest.xml file, add the app ID generated when the creating the app on HUAWEI Developers to the application section.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="APP ID"/>
4.Call the related APIs to display HUAWEI ID sign-in screen and authorization screen. The app can only access data upon user authorization.
Sign in via HMS Core SDK and apply for the scope to obtain the permissions to access the HUAWEI Health Kit APIs.
Code:
private void signInn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example.
// Developers need to add scopes according to their specific needs.
// View and save steps in HUAWEI Health Kit.
scopeList.add(new Scope( Scopes.HEALTHKIT_STEP_BOTH));
// View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_CALORIES_BOTH));
// View and save the heart rate data in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_DISTANCE_BOTH));
// 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.getContext(), 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();
final Context context = this.getContext();
// 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");
try {
readData();
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(context, "silentSignIn success", Toast.LENGTH_LONG).show();
}
}).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();
MeFragment.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
5.Build the condition for data query: a DataCollector object
Code:
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build();
6.Build time range and build condition-based query object.
Use the specified condition query object(call read Option) to call the data controller to query the sampling dataset.
Code:
public void readData() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-07-17 09:05:00");
ReadOptions readOptions = new ReadOptions.Builder()
.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
.read(DataType.DT_CONTINUOUS_CALORIES_BURNT)
.read(DataType.DT_CONTINUOUS_DISTANCE_DELTA)
.setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
.build();
Task<ReadReply> readReplyTask = dataController.read(readOptions);
readReplyTask.addOnSuccessListener(new OnSuccessListener<ReadReply>() {
@Override
public void onSuccess(ReadReply readReply) {
for (SampleSet sampleSet : readReply.getSampleSets()) {
showSampleSet(sampleSet);
Log.i(TAG,"*****************"+sampleSet);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
checkData.setText(e.toString()+"read");
}
});
}
7.the calories,distance and step are succesfully show in app.
Reference:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/overview-dev-android-0000001050071671
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.
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
{
"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"
}
Hello everyone,
Especially recently when we realized how important the “health” issue is for us, we learned how important it is to act in order to lead a healthy life. For the days when we worked in the home office and forgot to act like as a human, we can follow our daily steps, how many steps we have taken in 3 months and how many calories we have burned. We develop sample app to use this properties. We used these features with the help of Health Kit.
Before step into development progress, let’s examine what is Huawei Health Kit and what are the main functions.
Huawei Health Kit :
HUAWEI Health Kit allows ecosystem apps to access fitness and health data of users based on their HUAWEI ID and authorization. For consumers, Health Kit provides a mechanism for fitness and health data storage and sharing based on flexible authorization. For developers and partners, Health Kit provides a data platform and fitness and health open capabilities, so that they can build related apps and services based on a multitude of data types. Health Kit connects the hardware devices and ecosystem apps to provide consumers with health care, workout guidance, and ultimate service experience.
Main Functions :
· Data storage
Provides a data platform for developers to store fitness and health data.
· Data openness
Provides a wide range of fitness and health APIs and supports sharing of the various fitness and health data, including step count, weight, and heart rate.
· Data access authorization management
Provides settings for users and developers so users can manage developers’ access to their health and fitness data, guaranteeing users’ data privacy and legal rights.
· Device access
Provides hardware devices (including fitness and health devices) with APIs for measuring and uploading data through the standard Bluetooth protocol.
You can browse this page to examine it in more detail.
https://developer.huawei.com/consumer/en/hms/huaweihealth/
Development Process
We learned about Huawei Health Kit and its main functions. Now, we can move on development part. Primarily, we should create a project on App Gallery Connect. You can follow the steps from the link below.
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98
After all these steps, we need to apply for Health Kit.
Then, we need to select data and their permissions.
!!! To access health data we need to authenticate the user with Huawei ID.
Let’s continue by coding Data Controller to get our users’ step data.
Code:
private fun initDataController() {
val hiHealthOptions = HiHealthOptions.builder()
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_READ)
.build()
val signInHuaweiId =
HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions)
dataController = HuaweiHiHealth.getDataController(context!!, signInHuaweiId)
}
}
After creating the Data Controller, we write the read Daily function to get daily steps data of our users.
Code:
fun readDaily(startTime: Int, endTime: Int) {
val daliySummationTask =
dataController!!.readDailySummation(
DataType.DT_CONTINUOUS_STEPS_DELTA,
startTime,
endTime
)
daliySummationTask.addOnSuccessListener { sampleSet ->
sampleSet?.let { showSampleSet(it) }
}
daliySummationTask.addOnFailureListener { e ->
val errorCode: String? = e.message
val pattern: Pattern = Pattern.compile("[0-9]*")
val isNum: Matcher = pattern.matcher(errorCode)
when {
e is ApiException -> {
val eCode = e.statusCode
val errorMsg = HiHealthStatusCodes.getStatusCodeMessage(eCode)
}
isNum.matches() -> {
val errorMsg =
errorCode?.toInt()?.let { HiHealthStatusCodes.getStatusCodeMessage(it) }
}
else -> {
}
}
}
}
Let’s build the request body for reading activity records. We call the read method of the Data Controller to obtain activity records from the Health platform based on the conditions in the request body. Also, we should set time format. The daily hours reading format should be like this:
” yyyy-MM-dd hh: mm: ss “
Code:
fun getActivityRecord() {
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())
val startDate: Date = dateFormat.parse("yyyy-MM-dd hh:mm:ss")!!
val endDate: Date = dateFormat.parse("yyyy-MM-dd hh:mm:ss")!!
val readOptions = ReadOptions.Builder()
.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setTimeRange(
startDate.time,
endDate.time,
TimeUnit.MILLISECONDS
)
.build()
val readReplyTask = dataController!!.read(readOptions)
readReplyTask.addOnSuccessListener { readReply ->
Log.i("TAG", "Success read an SampleSets from HMS core")
for (sampleSet in readReply.getSampleSets()) {
showSampleSet(sampleSet)
}
}.addOnFailureListener { e ->
val errorCode: String? = e.message
val pattern: Pattern = Pattern.compile("[0-9]*")
val isNum: Matcher = pattern.matcher(errorCode)
when {
e is ApiException -> {
val eCode = e.statusCode
val errorMsg = HiHealthStatusCodes.getStatusCodeMessage(eCode)
}
isNum.matches() -> {
val errorMsg =
errorCode?.toInt()?.let { HiHealthStatusCodes.getStatusCodeMessage(it) }
}
else -> {
}
}
}
}
Bonus : I used pagination to displaying step data for better user experience and resource management.
Code:
var count = 0
var today = Calendar.getInstance()
var nextDay = Calendar.getInstance()
nextDay.add(Calendar.DATE, -20)
var dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
println("Today : " + dateFormat.format(Date(today.timeInMillis)))
stepViewModel.readToday()
stepViewModel.readDaily(dateFormat.format(Date(nextDay.timeInMillis)).toInt(), dateFormat.format(Date(today.timeInMillis)).toInt()-1)
binding.stepList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (!binding.stepList.canScrollVertically(1) && count<5) {
count++
var otherDay = Calendar.getInstance()
var nextDay = Calendar.getInstance()
otherDay.add(Calendar.DATE, -(20*count))
nextDay.add(Calendar.DATE, -((20*(count + 1)-1)))
stepViewModel.readDaily(dateFormat.format(Date(nextDay.timeInMillis)).toInt(), dateFormat.format(Date(otherDay.timeInMillis)).toInt())
}
}
})
Finally, we completed our development process. Let’s see how it looks in our project.
Conclusion
We have created an application where we can track our daily step count by taking advantage of the features provided by the Health Kit. I think it is necessary for all of us to face this reality. I hope it has been useful article for you. Your questions and opinions are very important to me.
References :
https://developer.huawei.com/consumer/en/hms/huaweihealth/
In the previous post, we learned the advantages of Account Kit: one-click sign-in authorization in any scenario, secure and reliable services, and convenient integration, as well as giving apps access to the global HUAWEI ID base of potential users. A QR code is also provided at the end of the post for you to download the demo app to experience HUAWEI ID sign-in authorization. The demo has integrated three Account Kit APIs (four in total), and is easy to develop. In this article, we'll show you the demo development to get you familiar with Account Kit.
Before you start, use a browser to scan the QR code below to try the demo app.
{
"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"
}
(Note: The app may collect relevant information for user statistics.)
Preparing for Demo Developmentl Install Android Studio 3.5 or later.
l Install JDK 1.8 or later.
l Use SDK Platform 19 or later.
l Use Gradle 4.6 or later.
l If you haven't already, register as a developer on HUAWEI Developers.
l Download the sample code of the demo from GitHub.
Configuring the Running Environment (2 minutes)1. Use Android Studio to open the demo project.
2. Go to File > Settings > Plugins > Marketplace, enter HMS Toolkit in the search box, and click Install. Note: HMS Toolkit must be version 5.2.0.300 or later.
For details, please refer to Installing HMS Toolkit.
3. Create a package and rename it to something like com.hxb.account in the project. Then, copy the code in the com.huawei.hms.accountsample package to your package, and change the value of package and applicationId to your package name. (Do not use the existing package name in the demo project because it is already registered on HUAWEI AppGallery.)
First, create a package. Move the MainActivity class to your package so that you can search for related files easily during the build.
Change package in the AndroidManifest.xml file to com.hxb.account.
Change applicationId in the build.gradle file to com.hxb.account.
4. Go to HMS > Configuration Wizard to check the environment configuration. If you have not signed in with a HUAWEI ID, Toolkit will first prompt you to do so.
On the Configuration Wizard page displayed, you are prompted that no app corresponding to the package name was detected under the signed-in HUAWEI ID.
Click Link to go to AppGallery Connect and create an app manually:
(a) Click Release.
(b) Click Add project.
(c) Create a project.
(d) Click Add app.
(e) Add the project.
After creating, go back to the Configuration Wizard page and click Retry. This time, the check will be successful.
5. Choose Account Kit.
On the Configuration Wizard page, click Add Kits and choose Account Kit.
The following page will be displayed.
6. Choose a certificate. You can choose Use Android debug certificate and click Generate to generate a certificate fingerprint, as shown in the following figure.
7. Click Next to automatically complete other configurations including toggling on the Account Kit switch in AppGallery Connect, configuring the signing certificate fingerprint, downloading the agconnect-services.json file to the project directory, configuring obfuscation scripts, and adding build dependencies and APK fingerprint required for integrating the Account SDK to the build.gradle file. Once these configurations are completed, the following page will be displayed. If you run into errors, please refer to the corresponding guide on the page.
Packaging and Testing the Demo on Remote Real Device Provided by ToolkitAfter configuration, go to HMS > Cloud Debugging to package and test the demo app.
Select the desired device model.
Click Run to test the demo app.
Key Code for Demo Development1. UI Design
Account Kit provides four main APIs for signing in, silently signing in, revoking authorization, and signing out. The demo app integrates the first three.
In the above figure, the Sign in with HUAWEI ID button is created with an encapsulated standard control. Please follow HUAWEI ID Sign-In Button Usage Rules when using the icon elements provided by Huawei.
Code:
<p style="line-height: 1.5em;"><com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
/>
1. Key Code for APIs
(1) Sign-in
Use case: Account Kit, compliant with OAuth 2.0 and OpenID Connect, supports sign-in in two modes: authorization code (for apps with their own servers only) and ID token modes. Select the mode you need.
Code:
private void signIn() {
mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = AccountAuthManager.getService(AccountActivity.this, mAuthParam);
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
}
As shown, setIdToken() means use the ID token mode for authorization. The other mode will show setAuthorizationCode() instead. Their difference will be described later. getSignInIntent() is the API for ID sign-in authorization.
Process the result after authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
// Successful sign-in.
// Obtain user information through parseAuthResultFromIntent.
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken:\n" + authAccount.getAccessToken());
Log.i(TAG, "OpenId:\n" + authAccount.getOpenId());
Log.i(TAG, "Email:\n" + authAccount.getEmail());
Log.i(TAG, "UnionId:\n" + authAccount.getUnionId());
// Download avatar by using AsyncTask.
NetService = new NetService(new URLPostHandler() {
@Override
public void PostHandler(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
textView.setText(authAccount.getDisplayName());
}
});
netService.execute(authAccount.getAvatarUriString());
} else {
Log.i(TAG, "signIn failed: " + ((ApiException)
authAccountTask.getException()).getStatusCode());
}
}
}
(2) Silent sign-in
Use case: Authorization is required only on first sign-in to your app using a HUAWEI ID. Subsequent sign-ins using the same HUAWEI ID do not require any authorization.
Code:
private void silentSignIn() {
Task<AuthAccount> task = mAuthManager.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
Log.i(TAG, "silentSignIn success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// If failed, use getSignInIntent.
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
signIn();
}
}
});
}
Call silentSignIn() to implement silent sign-in.
(3) Authorization revoking
Use case: To improve privacy security, users can unauthorize your app.
Code:
private void cancelAuthorization() {
Task<Void> task = mAuthManager.cancelAuthorization();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
imageView.setImageDrawable(null);
textView.setText("");
Log.i(TAG, "cancelAuthorization success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "cancelAuthorization failure:" + e.getClass().getSimpleName());
}
});
}
Call cancelAuthorization() to revoke authorization.
For more information about Account Kit, please visit:
l Development guide
l Codelab
l Video course (and the course for HMS Core 4.0.)
For more details, you can go to:
Our official website
Demo of Analytics Kit
Android SDK integration documentation
iOS SDK integration documentation
Web SDK integration documentation
Quick app SDK integration documentation
Checkout in forum