Service Scenario Description

SaveMyHeart App will give insight about how HMS Kits can be easily integrated into your existing health app which will help you alert users when heart rate reaches to maximum level with the help of Honor band. Here maximum heart rate can be calculated based on the user activity. In this code lab we are implementing below features with HMS kits.

Features

HMS Kits

Obtaining Runtime heart rate from Honor band with Health App

Health Kit

Obtaining Activity recognition

Location kit

What You Will Create

In this code lab, you will create a demo project and use the APIs of HUAWEI Location and Health Kit you can explore the following processes in the demo project:

What You Will Learn

In this code lab, you will learn how to:

Hardware Requirements

Software Requirements

Use the below link for preparing for the integration
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/config-agc-0000001050196065

  1. Enable the API permission for below kits from Project Setting > Manage APIs and enable the API permission.
    • Account Kit
    • Location Kit
  2. Apply for Health kit.
    • Login to Huawei AppGallery Connect
    • Click Health Kit
    • Click Apply for Health Kit

  3. Select the Heart rate data access permissions

    Now, you have successfully enabled HUAWEI Services and applied Health kit required for your app.

  4. Ensure Huawei Health app installed in device and Sync data to cloud is enabled.
    Steps: Open Huawei Health app -> Me -> Privacy management.

Use below links to Integrate HMS core SDK for following kits

  1. Location Kit
  2. Health Kit

User activity recognition screen

User heart rate from Honor Band

Class Diagram

Integration of HMS Location Kit

To use the activity identification service APIs of Location Kit, download and install HMS Core (APK) on your device, and integrate related SDKs into your project.
Use below link to integrate Huawei Location kit
HUAWEI Location Kit.

Step 1: Obtain user permission for device location access, prompt the user to enable location services if location is currently turned off, the app needs to request location or receive permission updates.

Java

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); mLocationRequest = new LocationRequest(); builder.addLocationRequest(mLocationRequest); LocationSettingsRequest locationSettingsRequest = builder.build(); settingsClient .checkLocationSettings(locationSettingsRequest) .addOnSuccessListener( new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { activityIdentificationService = ActivityIdentification.getService(HomePageActivity.this); pendingIntent = getPendingIntent(); getActivityIdentification(); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { ResolvableApiException rae = (ResolvableApiException) e; rae.startResolutionForResult(HomePageActivity.this, 0); } catch (IntentSender.SendIntentException sie) { Log.e(TAG, e.getMessage()); } break; } } });

Kotlin

val builder = LocationSettingsRequest.Builder() val mLocationRequest = LocationRequest() builder.addLocationRequest(mLocationRequest) val locationSettingsRequest = builder.build() mSettingsClient ?.checkLocationSettings(locationSettingsRequest) ?.addOnSuccessListener { mActivityIdentificationService = ActivityIdentification.getService(this@HomePageActivity) mPendingIntent = pendingIntent activityIdentification } ?.addOnFailureListener { e -> val statusCode = (e as ApiException).statusCode if (statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) { try { val rae = e as ResolvableApiException rae.startResolutionForResult(this@HomePageActivity, 0) } catch (ignored: SendIntentException) { Log.i(TAG, getString(R.string.createActivityIdentificationUpdates)) } } }

Step 2: To obtain the activity status of the user (for example, walking, running, or bicycling).

Java

@Override public void onReceive(Context context, Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_PROCESS_LOCATION.equals(action)) { ActivityIdentificationResponse activityIdentificationResponse = ActivityIdentificationResponse.getDataFromIntent(intent); List<ActivityIdentificationData> list = activityIdentificationResponse.getActivityIdentificationDatas(); Intent i = new Intent(); i.putExtra("Name", list.get(0).getIdentificationActivity()); i.putExtra("Value", list.get(0).getPossibility()); i.setAction("ACTIVITY_RECOGNITION"); context.sendBroadcast(i); }

Kotlin

override fun onReceive(context: Context, intent: Intent) { if (intent != null) { val action = intent.action if (ACTION_PROCESS_LOCATION == action) { val activityIdentificationResponse = ActivityIdentificationResponse.getDataFromIntent(intent) val list = activityIdentificationResponse.activityIdentificationDatas val ACTIVITY_RECOGNITION = "ACTIVITY_RECOGNITION" val i = Intent() i.putExtra(NAME, list[0].identificationActivity) i.putExtra(VALUE, list[0].possibility) i.action = ACTIVITY_RECOGNITION context.sendBroadcast(i) } } }

Integration of Health kit

HUAWEI Health Kit (Health Kit for short) 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.
Use below link to integrate Huawei Account kit
HUAWEI Health Kit

Step 1: Sign in with Huawei ID and get access to API calls to display the HUAWEI ID sign-in screen and authorization screen. The app can only access data upon user authorization.

Java

private void signIn() { List<Scope> scopeList = new ArrayList<>(); scopeList.add(new Scope(getString(R.string.URL))); HuaweiIdAuthParamsHelper authParamsHelper = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM); HuaweiIdAuthParams authParams = authParamsHelper.setIdToken() .setAccessToken() .setScopeList(scopeList) .createParams(); final HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(this.getApplicationContext(), authParams); Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn(); authHuaweiIdTask .addOnSuccessListener( new OnSuccessListener<AuthHuaweiId>() { @Override public void onSuccess(AuthHuaweiId huaweiId) { getHeartRate(); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception exception) { if (exception instanceof ApiException) { Intent signInIntent = authService.getSignInIntent(); HomePageActivity.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN); } } }); }

Kotlin

private fun signIn() { val scopeList: MutableList<Scope> = ArrayList() scopeList.add(Scope(getString(R.string.URL))) val authParamsHelper = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM) val authParams = authParamsHelper.setIdToken() .setAccessToken() .setScopeList(scopeList) .createParams() val authService = HuaweiIdAuthManager.getService(this.applicationContext, authParams) val authHuaweiIdTask = authService.silentSignIn() authHuaweiIdTask .addOnSuccessListener { getHeartRate } .addOnFailureListener { exception -> if (exception is ApiException) { val signInIntent = authService.signInIntent this@HomePageActivity.startActivityForResult(signInIntent, com.huawei.healthkitsampleapp.kotlin.HomePageActivity.REQUEST_SIGN_IN_LOGIN) } } }

Step 2. Obtain Huawei Id sign in result.

Java

@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); handleSignInResult(requestCode, data); } private void handleSignInResult(int requestCode, Intent data) { if (requestCode != REQUEST_SIGN_IN_LOGIN) { return; } HuaweiIdAuthResult result = HuaweiIdAuthAPIManager.HuaweiIdAuthAPIService.parseHuaweiIdFromIntent(data); if (result.isSuccess()) { getHeartRate(); } }

Kotlin

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) handleSignInResult(requestCode, data) } private fun handleSignInResult(requestCode: Int, data: Intent?) { if (requestCode != REQUEST_SIGN_IN_LOGIN) { return } val result = HuaweiIdAuthAPIManager.HuaweiIdAuthAPIService.parseHuaweiIdFromIntent(data) if (result.isSuccess) { getHeartRate } }

Step 3. Obtain Heart rate from connected Honor band.

Java

public void getHeartRate() { HiHealthDataStore.startReadingHeartRate( HomePageActivity.this, new HiRealTimeListener() { @Override public void onResult(int state) { } @Override public void onChange(int resultCode, String value) { if (resultCode == HiHealthError.SUCCESS) { try { JSONObject jsonObject = new JSONObject(value); mHeartRate = jsonObject.getInt(getString(R.string.hr_info));

Kotlin

get() { HiHealthDataStore.startReadingHeartRate( this@HomePageActivity, object : HiRealTimeListener { override fun onResult(state: Int) {} override fun onChange(resultCode: Int, value: String) { if (resultCode == HiHealthError.SUCCESS) { try { val jsonObject = JSONObject(value) mHeartRate = jsonObject.getInt(getString(R.string.hr_info))

Scenario 1

Signing in and Authorize the app to access Health data.

Scenario 2

Authorizing app to access data from Huawei Health data through Honor band.

Scenario 3

Obtaining Real-time Heart Rate from Honor band.

Well done. You have successfully built a SaveMyHeart app and learned how to:

  1. Location Kit
  2. Health Kit

To download the source code, please click the button below.
Download

Code copied