Tech Insights
Chirath Perera
December 14, 2020

Integrating Huawei HMS Core to an Existing Android Application

Integrating Huawei HMS Core to an Existing Android Application

In order to handle health fitness data

In this article, Iexplain how to integrate Huawei HMS Core into both existing and new androidapplications. This is possible as Huawei continues to use the open source coreAndroid operating system on its devices.

Huawei health kitprovides data such as Google fitness data. It opens fitness and health data fordevelopers, offering data aggregation, storage, and sharing capabilities forfitness and health apps and devices. It provides open APIs to read and writedata, and a sharing mechanism for consumers to authorise and revokeauthorisation as well.

Cloud API

Open capabilities on thecloud side support both web and phone apps. Developers can use RESTful APIs toaccess the Health Kit data platform. The app can read and write users’ fitnessand health data upon the data-type-specific user authorisation.

1. You have to create anapplication in Huawei console area. https://developer.huawei.com/consumer/en/console.

2. Downloadagconnect-services.json file. Go to Project setting > General manager inconsole.

3. Add downloadedagconnect-services file into app’s root directory in your code base.

4. Add below Maven dependency toproject level build.gradle

maven { url 'https://developer.huawei.com/repo/' }

5. Add below dependencies to applevel build.gradle

apply plugin: 'com.huawei.agconnect'

maven { url 'https://developer.huawei.com/repo/' }

buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
}
}

implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300'
implementation "com.huawei.hms:health:5.0.4.300"

6. Add meta tag into yourmanifest file.

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

The app id can be obtained from your Huawei console area.

7. Check if your device hasGoogle services available.

If you are going tointegrate Huawei HMS to an existing android project, then you have to checkwhether Google services are available in your device. If not, continue step 8onward.

int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.currentContext);
if (resultCode == ConnectionResult.SUCCESS){
add google services code here
} else {
add Huawei code here
};

8. Adding "HuaweiInit" and "Huawei Sign-In" services

 

view rawMainActivity.java hostedwith ❤ by GitHub

 

9.Getting the required stepsfrom Huawei Health

private class GetSteps extends AsyncTask<Void, Void,Void> {
       @Override
       protectedVoid doInBackground(Void... arg0) {

           Stringste = "0";

          HuaweiServices huaweiServices = new HuaweiServices(getActivity());
           if (huaweiServices.isGooglePlayServicesAvailable()){
              DataReadRequest readRequest = queryFitnessData(0);
              DataReadResult dataReadResult = Fitness.HistoryApi.readData(mApiClient,readRequest).await(1, TimeUnit.MINUTES);
              ste = printData(dataReadResult);
              sendLatestStepsToServer(ste);
           } else{
               HiHealthOptions hiHealthOptions =HiHealthOptions.builder()
                      .addDataType(com.huawei.hms.hihealth.data.DataType.DT_INSTANTANEOUS_HEIGHT,HiHealthOptions.ACCESS_READ)
                      .addDataType(com.huawei.hms.hihealth.data.DataType.DT_INSTANTANEOUS_HEIGHT,HiHealthOptions.ACCESS_WRITE)
                      .addDataType(com.huawei.hms.hihealth.data.DataType.DT_CONTINUOUS_STEPS_DELTA,HiHealthOptions.ACCESS_READ)
                      .addDataType(com.huawei.hms.hihealth.data.DataType.DT_CONTINUOUS_STEPS_DELTA,HiHealthOptions.ACCESS_WRITE)
                      .build();
              AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions);

              DataController dataController = HuaweiHiHealth.getDataController(getActivity(),signInHuaweiId);


              Task<SampleSet> todaySummationTask =dataController.readTodaySummation(com.huawei.hms.hihealth.data.DataType.DT_CONTINUOUS_STEPS_DELTA);
              todaySummationTask.addOnSuccessListener(new OnSuccessListener<SampleSet>(){
                  @Override
                  public void onSuccess(SampleSet sampleSet) {
                      logger("Success read today summation from HMS core");
                      isLinkedHuawei = true;
                      if (sampleSet != null) {
                          showSampleSet(sampleSet);
                          sendLatestStepsToServer(steps);
                      }
                  }
              });
              todaySummationTask.addOnFailureListener(new OnFailureListener() {
                  @Override
                   public void onFailure(Exception e) {
                      isLinkedHuawei = true;
                      String errorCode = e.getMessage();
                      String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                      logger(errorCode + ": " + errorMsg);
                      Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                  }
              });

           }
           returnnull;
       }

   

   }private StringshowSampleSet(SampleSet sampleSet) {

  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

   for (SamplePointsamplePoint : sampleSet.getSamplePoints()) {
       logger("Samplepoint type: " + samplePoint.getDataType().getName());
       logger("Start:" + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
       logger("End:" + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
       for (com.huawei.hms.hihealth.data.Fieldfield : samplePoint.getDataType().getFields()) {
          logger("Field: " + field.getName() + " Value:" + samplePoint.getFieldValue(field));
       }
   }


}

When you run the application you can see a page to link the application to Huawei Health Kit.

Huawei Health Kitprovides APIs to read, add, delete, and modify fitness and health data.

By integrating theHuawei Health SDK into their apps, developers can call the Huawei Health KitAPIs to write users’ fitness and health data to the data platform.

To make this happen,developers need to:

·        Register aHuawei ID on the Huawei Developers website. Then, create an app, configure theapp information, and enable the Huawei Health Kit service on the HuaweiDevelopers Console.

·        Create aproject with Android Studio IDE and configure the SDK on which Huawei HealthKit depends.

·        ImplementHUAWEI Health Kit API calling and debugging.

Hope you liked thispost. Stay tuned for more!

Reference — https://developer.huawei.com/consumer/en/doc/health-introduce-0000001053684429-V5