[Huawei Developers] John Wo:
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.

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):

maven { url ‘http://developer.huawei.com/repo/’ }

9) Enter the below Health Kit, account kit and auth service dependencies in the dependencies section:

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.

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.

<meta-data
android:name="com.huawei.hms.client.appid"
android:value="Your app id"/>

12) Add the below permissions to manifest file.

<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().

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.

/**
* 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