DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Turn Your App into a Handy Health Assistant
  • The Complete Guide to Stream API and Collectors in Java 8
  • How to Build a Pokedex React App with a Slash GraphQL Backend
  • Using VB.NET To Check for Proxy and VPN With IP2Location.io Geolocation API

Trending

  • Teradata Performance and Skew Prevention Tips
  • A Guide to Container Runtimes
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Contextual AI Integration for Agile Product Teams
  1. DZone
  2. Data Engineering
  3. Data
  4. Allow Users to Track Fitness Status in Your App

Allow Users to Track Fitness Status in Your App

Endow your app with the ability to manage fitness status and obtain real-time fitness data.

By 
Jackson Jiang user avatar
Jackson Jiang
DZone Core CORE ·
Sep. 26, 22 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.8K Views

Join the DZone community and get the full member experience.

Join For Free

During workouts, users expect to be able to track their status and data in real time within the health or fitness app on their phones. Huawei phone users can link a piece of equipment, like a treadmill or spinner bike, via the Huawei Health app, and start and track their workout within the app. As a fitness and health app developer, you can read activity records from the Huawei Health app, and display the records in your app. It is even possible to control the workout status directly within your app, and obtain real-time activity data, without having to redirect users to the Huawei Health app, which helps users conveniently track their workout and greatly enhances the user experience. Here is how.

HMS Core Health Kit provides a wide range of capabilities for fitness and health app developers. Its extended capabilities open up a wealth of real-time activity and health data and solutions specific to different scenarios. For example, after integrating the extended capabilities, you can call the APIs for starting, pausing, resuming, and stopping activities, to control activity status directly within your app, without redirecting users to the Huawei Health app. The Huawei Health app runs unobtrusively in the background throughout this entire process.

The extended capabilities also offer APIs for obtaining and halting the collection of real-time workout data. To prevent data loss, your app should call the API for obtaining real-time data before the workout starts, and avoid calling the API for halting the collection of real-time data before the workout ends. If the user links their phone with a Huawei wearable device via the Huawei Health app, the workout status in your app will be synched to the wearable device. This means that the wearable device will automatically display the workout screen when the user starts a workout in your app and will stop displaying it as soon as the workout is complete. Make sure that you have applied for the right scopes from Huawei and obtained authorization from users before the API call. Otherwise, API calls will fail. The following workouts are currently supported: outdoor walking, outdoor running, outdoor cycling, indoor running (on a treadmill), elliptical machine, rowing machine, and indoor cycling.

Demo

Health data

Preparations

Applying for Health Kit

Before applying for Health Kit, you will need to apply for the Account Kit first.

Integrating the HMS Core SDK

Before integrating the Health SDK, integrate the Account SDK first.

Before getting started, you need to integrate the HMS Core SDK into your app using Android Studio. Make sure that you use Android Studio V3.3.2 or later during the integration of the Health Kit.

Development Procedure

Starting Obtaining Real-time Activity Data

1. Call the registerSportData method of the HiHealthDataStore object to start obtaining real-time activity data.

2. Check the returned result through the request parameter HiSportDataCallback.

The sample code is as follows:

Java
 
HiHealthDataStore.registerSportData(context, new HiSportDataCallback() {    
   
    @Override    
    public void onResult(int resultCode) {
        // API calling result.
        Log.i(TAG, "registerSportData onResult resultCode:" + resultCode);   
    }
    @Override    
    public void onDataChanged(int state, Bundle bundle) {
        // Real-time data change callback.
        Log.i(TAG, "registerSportData onChange state: " + state);        
        StringBuffer stringBuffer = new StringBuffer("");              
        if (state == HiHealthKitConstant.SPORT_STATUS_RUNNING) {
            Log.i(TAG, "heart rate : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_HEARTRATE));
            Log.i(TAG, "distance : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DISTANCE));
            Log.i(TAG, "duration : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DURATION));
            Log.i(TAG, "calorie : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_CALORIE));
            Log.i(TAG, "totalSteps : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_STEPS));
            Log.i(TAG, "totalCreep : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_CREEP));
            Log.i(TAG, "totalDescent : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_DESCENT));
        }    
    }
});

Call the UnregisterSportData Method of the HiHealthDataStore Object To Stop Obtaining the Real-time Activity Data.

  1. Check the returned result through the request parameter HiSportDataCallback.

The sample code is as follows:

 
HiHealthDataStore.unregisterSportData(context, new HiSportDataCallback() {    
    JSONObject jsonResult
    @Override    
    public void onResult(int resultCode) {
        // API calling result.
        Log.i(TAG, "unregisterSportData onResult resultCode:" + resultCode);   
    }
    @Override    
    public void onDataChanged(int state, Bundle bundle) {
        // The API is not called at the moment.
    }
});

Starting an Activity According to the Activity Type

1. Call the startSport method of the HiHealthDataStore object to start a specific type of activity.

2. Use the ResultCallback object as a request parameter to get the query result.

The sample code is as follows:

Java
 
// Outdoor running.
int sportType = HiHealthKitConstant.SPORT_TYPE_RUN;
HiHealthDataStore.startSport(context, sportType, new ResultCallback() {
    @Override
    public void onResult(int resultCode, Object message) {
        if (resultCode == HiHealthError.SUCCESS) {
            Log.i(TAG, "start sport success");
        }
    }
});

3. For activities that depend on equipment like treadmills, rowing machines, elliptical machines, and stationary bikes, you will need to first check whether the relevant equipment has been paired in the Huawei Health app before starting the activity. The following uses a rowing machine as an example.

  • If there is one rowing machine paired, this machine will be connected by default, and the activity will then start in the background.
  • If the app is paired with more than one rowing machine, a pop-up window will display prompting the user to select a machine. After the user makes their choice, the window will disappear and the workout will start in the background.
  • If the app is not paired with any rowing machine, the user will be redirected to the device pairing screen in the Huawei Health app, before being returned to your app. The workout will then start in the background.

Scanning

Starting an Activity Based on the Device Information

1. Call the startSportEx method of the HiHealthDataStore object, and pass the StartSportParam parameter for starting the activity. You can control whether to start the activity in the foreground or in the background by setting CharacteristicConstant.SportModeType.

2. Use the ResultCallback object as a request parameter to get the activity starting result.

The sample code is as follows:

Java
 
// The following takes the rowing machine as an example.
// MAC address, with every two digits separated by a colon (:), for example, 11:22:33:44:55:66.
String macAddress = "11:22:33:44:55:66" ;
// Whether FTMP is supported. 0: no; 1: yes.
int isSupportedFtmp = CharacteristicConstant.FtmpType.FTMP_SUPPORTED.getFtmpTypeValue();
// Device type: rowing machine.
int deviceType = CharacteristicConstant.DeviceType.TYPE_ROWER_INDEX.getDeviceTypeValue();
// Activity type: rowing machine.
int sportType = CharacteristicConstant.EnhanceSportType.SPORT_TYPE_ROW_MACHINE.getEnhanceSportTypeValue();
// Construct startup parameters for device connection and activity control.
StartSportParam param = new StartSportParam(macAddress, isSupportedFtmp, deviceType, sportType);
// Whether to start the activity in the foreground (0) or background (1).
param.putInt(HiHealthDataKey.IS_BACKGROUND,
    CharacteristicConstant.SportModeType.BACKGROUND_SPORT_MODE.getType());
HiHealthDataStore.startSportEx(mContext, param, new ResultCallback() {
    @Override
    public void onResult(int resultCode, Object message) {
        
        if (resultCode == HiHealthError.SUCCESS) {
            Log.i(TAG, "start sportEx success");
        }
    }
});

Stopping an Activity

1. Call the stopSport method of the HiHealthDataStore object to stop a specific type of activity. Note that you cannot use this method to stop activities started in the foreground.

2. Use the ResultCallback object as a request parameter to get the query result.

The sample code is as follows:

Java
 
HiHealthDataStore.stopSport(context, new ResultCallback() {
    @Override
    public void onResult(int resultCode, Object message) {
        if (resultCode == HiHealthError.SUCCESS) {
            Log.i(TAG, "stop sport success");
        }
    }
});

Conclusion

Huawei phone users can use the Huawei Health app to bind wearable devices, start a workout and control their workout status, and track their workouts over time. When developing a fitness and health app, you can harness the capabilities of Health Kit and the Huawei Health app to get the best of all worlds: easy workout management free of annoying redirections. By calling the APIs provided by the kit's extended capabilities, you will be able to start, pause, resume, and stop workouts directly in your app, or obtain real-time workout data from the Huawei Health app and display it in your app, with Huawei Health running in the background. This will considerably enhance the user experience and make your fitness and health app much more appealing to a wider audience.

API Machine Software development kit User experience app Data (computing) Fitness (Apple) Health (Apple) Object (computer science) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Turn Your App into a Handy Health Assistant
  • The Complete Guide to Stream API and Collectors in Java 8
  • How to Build a Pokedex React App with a Slash GraphQL Backend
  • Using VB.NET To Check for Proxy and VPN With IP2Location.io Geolocation API

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!