Coder Social home page Coder Social logo

matinzd / react-native-health-connect Goto Github PK

View Code? Open in Web Editor NEW
156.0 7.0 27.0 1.98 MB

React native library for health connect (Android only)

Home Page: http://matinzd.github.io/react-native-health-connect

License: MIT License

Kotlin 67.16% JavaScript 1.38% Ruby 0.99% Shell 1.93% Swift 0.03% C 0.05% Objective-C 1.19% Objective-C++ 0.50% TypeScript 26.76%
health-connect react-native fitness health-sdk

react-native-health-connect's Introduction

React Native Health Connect


This library is a wrapper around Health Connect for react native. Health Connect is an Android API and platform. It unifies data from multiple devices and apps into an ecosystem. For Android developers, it provides a single interface for reading and writing a user’s health and fitness data. For Android users, it offers a place for control over which apps have read and/or write access to different types of data. Health Connect also provides on-device storage. Read more here.

Requirements

  • Health Connect needs to be installed on the user's device. Starting from Android 14 (Upside Down Cake), Health Connect is part of the Android Framework. Read more here.
  • Health Connect API requires minSdkVersion=26 (Android Oreo / 8.0).
  • If you are planning to release your app on Google Play, you will need to submit a declaration form.

Installation

To install react-native-health-connect, use the following command:

yarn add react-native-health-connect

For version 2 onwards, please add the following code into your MainActivity.kt within the onCreate method:

package com.healthconnectexample

+ import android.os.Bundle
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
+ import dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate

class MainActivity : ReactActivity() {
  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  override fun getMainComponentName(): String = "HealthConnectExample"

+ override fun onCreate(savedInstanceState: Bundle?) {
+   super.onCreate(savedInstanceState)
+   // In order to handle permission contract results, we need to set the permission delegate.
+   HealthConnectPermissionDelegate.setPermissionDelegate(this)
+ }

  /**
   * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
   * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
   */
  override fun createReactActivityDelegate(): ReactActivityDelegate =
    DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}

Expo installation

This package cannot be used in the Expo Go app, but it can be used with custom managed apps. Just add the config plugin to the plugins array of your app.json or app.config.js:

First install the package with yarn, npm, or expo install.

expo install react-native-health-connect

Then add the prebuild config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "plugins": ["react-native-health-connect"]
  }
}
  • Edit your app.json again and add this
{
  "expo": {
    ...
    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "compileSdkVersion": 34,
            "targetSdkVersion": 34,
            "minSdkVersion": 26
          },
        }
      ]
    ]
   ...
  }
}

Then rebuild the native app:

  • Run expo prebuild
  • Rebuild the app
    • yarn android -- Build on Android.

If the project doesn't build correctly with yarn android, please file an issue and try setting the project up manually.

Finally create a new EAS development build

eas build --profile development --platform android

Example

A quick example at a glance:

import {
  initialize,
  requestPermission,
  readRecords,
} from 'react-native-health-connect';

const readSampleData = async () => {
  // initialize the client
  const isInitialized = await initialize();

  // request permissions
  const grantedPermissions = await requestPermission([
    { accessType: 'read', recordType: 'ActiveCaloriesBurned' },
  ]);

  // check if granted

  const result = await readRecords('ActiveCaloriesBurned', {
    timeRangeFilter: {
      operator: 'between',
      startTime: '2023-01-09T12:00:00.405Z',
      endTime: '2023-01-09T23:53:15.405Z',
    },
  });
  // {
  //   result: [
  //     {
  //       startTime: '2023-01-09T12:00:00.405Z',
  //       endTime: '2023-01-09T23:53:15.405Z',
  //       energy: {
  //         inCalories: 15000000,
  //         inJoules: 62760000.00989097,
  //         inKilojoules: 62760.00000989097,
  //         inKilocalories: 15000,
  //       },
  //       metadata: {
  //         id: '239a8cfd-990d-42fc-bffc-c494b829e8e1',
  //         lastModifiedTime: '2023-01-17T21:06:23.335Z',
  //         clientRecordId: null,
  //         dataOrigin: 'com.healthconnectexample',
  //         clientRecordVersion: 0,
  //         device: 0,
  //       },
  //     },
  //   ],
  // }
};

Alternatives

For iOS there are two alteranatives you can use which is very similar to Health Connect on Android. First one is @kingstinct/react-native-healhkit and the other one is react-native-health. These options are similar in functionality and can help you manage your health data on iOS.

Documentation

More examples and full documentation can be found here

Features

  • Typescript ✅
  • Supports both old and new architecture ✅

License

MIT

react-native-health-connect's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-health-connect's Issues

React-native cli android build fail after install lib

Describe the bug
I have react native cli project with react naive version "react-native": "0.70.1".

After installing lib through yarn -> yarn add react-native-health-connect@latest
I am not able to run android project getting below error ->

FAILURE: Build failed with an exception.

  • What went wrong:
    Could not determine the dependencies of task ':react-native-health-connect:compileDebugAidl'.

Could not resolve all task dependencies for configuration ':react-native-health-connect:debugCompileClasspath'.
Could not find com.facebook.react:react-native:.
Required by:
project :react-native-health-connect

Is this lib not work for react-native cli project?

Expo build fails for specified SDK versions

Describe the bug
When I try to create an internal distribution build on Expo (non-development build), I'm getting this error around SDK versioning compatibility:

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.

---

- What went wrong:

Execution failed for task ':app:checkReleaseAarMetadata'.

> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction

> 3 issues were found when checking AAR metadata:

       1.  Dependency 'androidx.health.connect:connect-client:1.1.0-alpha03' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs.

       :app is currently compiled against android-33.

       Also, the maximum recommended compile SDK version for Android Gradle plugin 7.4.1 is 33.

       Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdkVerion of at least 34.
       
       Note that updating a library or application's compileSdkVersion (which allows newer APIs to be used) can be done separately from updating targetSdkVersion (which opts the app in to new runtime behavior) and minSdkVersion (which determines which devices the app can be installed on).

       2.  Dependency 'androidx.core:core-ktx:1.12.0-alpha05' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs.

       :app is currently compiled against android-33.

       Also, the maximum recommended compile SDK version for Android Gradle plugin 7.4.1 is 33.

       Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdkVerion of at least 34.

       Note that updating a library or application's compileSdkVersion (which allows newer APIs to be used) can be done separately from updating targetSdkVersion (which opts the app in to new runtime behavior) and minSdkVersion (which determines which devices the app can be installed on).

       3.  Dependency 'androidx.core:core:1.12.0-alpha05' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs.

       :app is currently compiled against android-33.

       Also, the maximum recommended compile SDK version for Android Gradle plugin 7.4.1 is 33.

       Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdkVerion of at least 34.

       Note that updating a library or application's compileSdkVersion (which allows newer APIs to be used) can be done separately from updating targetSdkVersion (which opts the app in to new runtime behavior) and minSdkVersion (which determines which devices the app can be installed on).

My app.config.js matches the config that the README specifies:

    plugins: [
      'react-native-health-connect',
      [
        'expo-build-properties',
        {
          android: {
            compileSdkVersion: 33,
            targetSdkVersion: 33,
            minSdkVersion: 26
          }
        }
      ]
    ],

When I bump to 34 on both compile and target, the build succeeds. I'm using the latest version of this library. Happy to open a PR to update the documentation if bumping the Sdk version is the correct solution!

Sleep data is missing

@matinzd First of all very good work.
Sleep data is missing. I saw it is not implemented yet, Can you prioritise sleep data? Humble request.

Task :react-native-health-connect:compileDebugKotlin FAILED

I have a question regarding the react-native-health-connect package/library. I have installed the package, but when I build my app, an error appears, indicating that there is a problem with the package.

I have been using this: "react-native": "0.64.3", java 15.0.1 versions of these programming languages in my project.
And i have also installed "react-native-health-connect": "0.1.0-alpha.3" package in my project.

I was wondering if you could help me with this package and if you are aware of the issue that is causing the error. Additionally, I was curious about the recommended versions of JVM and/or react-native to use in order to avoid this problem.
I would greatly appreciate any information or guidance you can provide on this matter.

Here is a example of an error that appears:

Task :react-native-health-connect:compileDebugKotlin FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-health-connect:compileDebugKotlin'.

A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
Compilation error. See log for more details

And also a screenshot of an error:
hc

Thank you for your time and expertise.

"Service Not Available" Error during Initialization on emulators

Describe the bug
I am encountering an error while trying to initialize the application using the initialize() function. The error message I receive is "Service not available." This issue occurs specifically when I'm running the application on an emulator.

To Reproduce
Steps to reproduce the behavior:

  1. Launch the device emulator using react-native run-android.
  2. Connect a watch emulator to the running device emulator.
  3. Invoke the initialize() method to initiate the application.
  4. Observe the error message displayed in the console:

Screenshots
Screenshot 2023-08-21 at 4 05 53 PM

Additional Information:

  • have verified that the watch emulator is correctly connected to the device emulator by inspecting the development server's logs.
  • I've attempted to disconnect and reconnect the watch emulator, as well as restarting both the device and watch emulators, but the error persists.

Question: Synchronise Data

I see that Health connect provides functionality to regularly synchronise data. Can this library work with that ? or I would have to come up with my own implementations ?

ref: Synchronise Data

"Error: Error not specified" on insertRecords

Describe the bug
I've managed to initialize and requestPermission, but when calling insertRecords it throws [Error: Error not specified.].

Please advise if there's any way to debug this from my end.

To Reproduce
Steps to reproduce the behavior:

  1. Add
<uses-permission android:name="android.permission.health.WRITE_EXERCISE"/>
  1. Call
await initialize()
  1. Call
await requestPermission([{accessType: 'write', recordType: 'ExerciseSession'}]);
  1. Call
await insertRecords([
    {
      recordType: 'ExerciseSession',
      exerciseType: 8,
      startTime: '2023-09-12T09:30:13.982Z',
      endTime: '2023-09-12T09:39:49.241Z',
    },
  ]);

Expected behavior
insertRecords should resolve without errors

Environment:

  • Health Connect Version: 1.2.0
  • React Native Version: 0.69.9
  • New architecture enabled: No

Thank you for a nice and well written library ☺️

Able to filter out manually added steps

Describe the bug
First thanks for this library!

Is there a way to filter out manually added steps?

To Reproduce
Add activity in Google Fit > Add steps > Save

Reading records

    const records = await readRecords('Steps', {
      timeRangeFilter: {
        operator: 'between',
        startTime: startOfDay(new Date()).toISOString(),
        endTime: endOfDay(new Date()).toISOString(),
      },
    });
    
    console.log('records', records);

Output

    {
        "count": 1,
        "endTime": "2023-11-13T13:10:01.770Z",
        "metadata": {
            "clientRecordId": null,
            "clientRecordVersion": 0,
            "dataOrigin": "com.google.android.apps.fitness",
            "device": 0,
            "id": "fed4b274-7df5-407a-9244-ceffdfd84fee",
            "lastModifiedTime": "2023-11-13T13:10:17.455Z",
            "recordingMethod": 0
        },
        "startTime": "2023-11-13T12:40:01.769Z"
    }

Expected behavior
In recordingMethod should be 3

Screenshots
n/a

Environment:
n/a

Expo 49 failing 'expo doctor' because of @expo/[email protected] dependency

When using Expo 49 and installing react-native-health-connect the command expo-doctor fails because of the @expo/config-plugins dependency version.

This is the error:
Screenshot 2023-07-16 at 22 33 02

To reproduce:

  1. initialize a new Expo project with Expo 49
  2. Install react-native-health-connect
  3. Run expo-doctor

I'm guessing the dependency @expo/config-plugins could be moved to devDependencies - potentially supplemented with an peerDependency with a loose version?

Periodic Updates

I'm trying to achieve periodic updates for the readRecords function.
Since Android 12 services are not available if the app is terminated.
Therefore I'm not able to use the existing library for creating a background/foreground job.

I started creating a native module using this library, which will be started/stopped using the bridge and uses WorkManager for requesting updates.

HealthConnectModule.java

public class HealthConnectModule extends ReactContextBaseJavaModule {

    private Context mContext;
    private PeriodicWorkRequest workRequest;

    HealthConnectModule(@Nonnull ReactApplicationContext reactContext) {
        super(reactContext);
        mContext = reactContext;
        workRequest = new PeriodicWorkRequest.Builder(HealthConnectBackgroundWorker.class, 15, TimeUnit.MINUTES).build();
    }

    @ReactMethod
    public void startBackgroundWork() {
        WorkManager.getInstance(mContext).enqueueUniquePeriodicWork("HealthConnectTask", 
ExistingPeriodicWorkPolicy.KEEP, workRequest);
    }

    @ReactMethod
    public void stopBackgroundWork() {
        WorkManager.getInstance(mContext).cancelUniqueWork("HealthConnectTask");
    }

    @Nonnull
    @Override
    public String getName() {
        return "HealthConnectModule";
    }
}

HealthConnectBackgroundWorker.java

public class HealthConnectBackgroundWorker extends Worker {
    private Context context;
    HealthConnectManager healthConnectManager;

    public HealthConnectBackgroundWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        this.context = context;
    }
    
    @NonNull
    @Override
    public Result doWork() {
        WritableArray scope = new WritableNativeArray();
        scope.pushString("app.example");

        ReactApplicationContext reactApplicationContext = new ReactApplicationContext(context);

        healthConnectManager = new HealthConnectManager(reactApplicationContext);
        healthConnectManager.initialize(scope, new Promise() {
            @Override
            public void resolve(@Nullable Object o) {
                WritableMap innerMap = new WritableNativeMap();
                innerMap.putString("operator", "between");
                innerMap.putString("startTime", "2023-01-09T12:00:00.405Z");
                innerMap.putString("endTime", "2023-02-09T12:00:00.405Z");
                WritableMap map = new WritableNativeMap();
                map.putMap("timeRangeFilter", innerMap);
                healthConnectManager.readRecords("ExcersiceSession", map, recordPromise);
            }

            @Override
            public void reject(String s, String s1) {
                Log.w("hctask", "initFailed1: " +s+s1);
            }
            ...

Right now, my promise gets rejected with the exception SERVICE_UNAVAILABLE.
Is there any better approach? It should be doable, because there are already apps requesting data in the background while the app is terminated.

Thank you in advance 👍

requestPermission crashes the app

Describe the bug
requestPermission crashes the app after the permissions have been granted from HealthConnect screen. If the permissions are granted previously, the app crashes immediately
To Reproduce
Steps to reproduce the behavior:

  1. Using the example code in this repo, trigger requestPermission
  2. Allow all
  3. Apply
  4. Crash happens
    Or set Allow All permissions from Health Connect settings for the app and then trigger requestPermission

Crash happens even if you tap on Cancel instead of Allow permission

Expected behavior
Crash should not happen. A permissions list should be returned by the promise
Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • Health Connect Version: 1.0.1
  • React Native Version: 0.69.7
  • New architecture enabled: No

Tested on 2 different real devices:

  1. S9+ with Android 10
  2. S22Ultra with Android 13

I am getting empty result like ActiveCaloriesBurned: []

My AndroidManifest.xml file is:

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
<uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
<uses-permission android:name="android.permission.health.READ_SLEEP"/>
<uses-permission android:name="android.permission.health.READ_STEPS"/>
<uses-permission android:name="android.permission.health.READ_WEIGHT"/>
<uses-permission android:name="android.permission.health.READ_HEIGHT"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE"/>

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
    android:launchMode="singleTask"
    android:windowSoftInputMode="adjustResize"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
      <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
    </intent-filter>
  </activity>
</application>

and my app.tsx file is:

import React, { useEffect } from 'react';
import type {PropsWithChildren} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  useColorScheme,
} from 'react-native';

import {
  Colors,
  Header,
} from 'react-native/Libraries/NewAppScreen';

import {
  initialize,
  requestPermission,
  readRecords,
} from 'react-native-health-connect';


function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';


    
  const readSampleData = async () => {
    // initialize the client
    const isInitialized = await initialize();
    if(isInitialized){
       // request permissions
    const grantedPermissions = await requestPermission([
      { accessType: 'read', recordType: 'ActiveCaloriesBurned' },
      { accessType: 'read', recordType: 'BloodGlucose' },
    ]);
    
    const resultActiveCaloriesBurned = await readRecords('ActiveCaloriesBurned', {
      timeRangeFilter: {
        operator: 'between',
        startTime: '2023-01-09T12:00:00.405Z',
        endTime: new Date().toISOString(),
      },
    });
  
    const resultBloodGlucose = await readRecords('BloodGlucose', {
      timeRangeFilter: {
        operator: 'between',
        startTime: '2023-01-09T12:00:00.405Z',
        endTime: new Date().toISOString(),
      },
    });
  
    console.log("Result is: ", resultActiveCaloriesBurned, resultBloodGlucose);
    
  
    }else{
      console.log("Sorry! something went wrong!");
    }
  
  };
  
  useEffect(()=>{
    readSampleData();
  }, [])
  

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
      
      </ScrollView>
    </SafeAreaView>
  );
}


export default App;

Task ':react-native-health-connect:compileDebugAidl' FAILED

Hi there, at first I'd like to thank for this library, just in time. I'm trying to build my project after installing this lib, but it fails.

My react native version was 0.64.0, but I saw the comment that it's better to use this lib with version 67+, so I manually upgraded it. Currently that's my setup:

  • Health Connect Version: 1.0.0
  • React Native Version: 0.70.0
  • New architecture enabled: No
    I also tried to run this lib having my react native version 0.64.0, had the same error.

I'm not strong with the native part, so may be you could have any suggestions what could be wrong. Please tell me if I need to share some more info, first time making a report.

image

image

Thank you for your time and expertise.

Question

I'm migrating project from expo to CLI, is this package is supported in CLI?
If not than any suggestions to do same thing in CLI?

Integration works on a test device when I run it, but does not work on a build from the play store

Describe the bug
The health connect integration works on a test device when I run and test it. But when I try to install it via Play Store it shows the following popup attached as a screen capture.

To Reproduce
Steps to reproduce the behavior:

  1. https://play.google.com/store/apps/details?id=com.fitpanda
  2. Sign up and go on user profile and try to enable health connect.

Expected behavior

  1. It should show a prompt to enable steps in health connect as it shows on a test device.

WhatsApp Image 2023-08-03 at 11 45 25 AM

Screencapture for the bug
https://github.com/matinzd/react-native-health-connect/assets/5388679/0316905e-90f1-43ab-b1ab-2d8e428c2270

Environment:

Error: Unable to resolve module when running metro on example app

Description:
When trying to run the example app, it builds fine but Metro crashes with the following error:

error: Error: Unable to resolve module @babel/runtime/helpers/interopRequireDefault from /Users/michaeln/Desktop/react-native-health-connect/src/errors.ts: @babel/runtime/helpers/interopRequireDefault could not be found within the project.
> 1 | export class HealthConnectError extends Error {
    | ^
  2 |   constructor(message: string, method: string) {
  3 |     super(`HealthConnect.${method}: ${message}`);
  4 |   }
    at ModuleResolver.resolveDependency (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:150:15)
    at DependencyGraph.resolveDependency (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/node-haste/DependencyGraph.js:282:43)
    at Object.resolve (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/lib/transformHelpers.js:176:21)
    at Graph._resolveDependencies (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/DeltaBundler/Graph.js:476:35)
    at Graph._processModule (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/DeltaBundler/Graph.js:261:38)
    at async Graph._addDependency (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/DeltaBundler/Graph.js:372:20)
    at async Promise.all (index 3)
    at async Graph._processModule (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/DeltaBundler/Graph.js:322:5)
    at async Graph._addDependency (/Users/michaeln/Desktop/react-native-health-connect/example/node_modules/metro/src/DeltaBundler/Graph.js:372:20)
    at async Promise.all (index 5)

Steps to reproduce the behavior:

  1. run npm start in react-native-health-connect/example

Screenshot from device:
Screenshot_20240211-184712_React Health Connect

Environment:

  • Health Connect Version:1.1.0-alpha06
  • React Native Version: 0.73.1
  • New architecture enabled: No

Cannot Seem to get Blood Pressure data

const readSampleDat = () => {
readRecords('BloodPressure', {
timeRangeFilter: {
operator: 'between',
startTime: '2023-12-05T10:00:00.405Z',
endTime: '2023-12-05T23:53:15.405Z',
},
}).then((result) => {
console.log('Retrieved records: ', JSON.stringify({ result }, null, 2));
});

Cannot get result from permission class: ActiveCaloriesBurned

Describe the bug
When requesting permissions on the first launch of my app it didn't show permission for calories. And when i check on the health connect app the permission didn't enable, and i try to enable it manually but when i open my app and log the result, the result is still an empty array

To Reproduce
Steps to reproduce the behavior:

  1. Add this permission on AndroidManifest.xml
  2. Launch the App
  3. Request permission prompt is showed but not showing calory permission

Expected behavior
Show the permission for calory and the result

Screenshots

  • Permission from health connect app
    WhatsApp Image 2024-02-19 at 14 23 49_e254cc8c
  • Enable calories manual from health connect app
    WhatsApp Image 2024-02-19 at 14 23 49_5cde1b80
  • This what i get the granted permissions and result from react native health connect
    image

Environment:

  • Health Connect Version: 1.2.3
  • React Native Version: 0.73.4

Cannot resolve 'main' module

react-native:  0.64.0
react: 17.0.1
react-native-health-connect: 0.0.1

I have followed the install instructions, but when I run my react-native project (using react-native run-android) I receive the following error:

Error: While trying to resolve module `react-native-health-connect` from file `...src\containers\HealthConnect\index.js`, the package `...node_modules\react-native-health-connect\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved

Any assistance would be greatly appreciated.

Thanks,
Graham.

Latest changes are not released

Hey @matinzd !...

Thanks for the lib.
Right now I can't use changes from your last commit where you've migrated to the latest Health connect SDK and added few more methods to RN module.

Is it possible to have new version released ?
Thx!

Accessing the raw sensor data?

How can we access the raw sensor data from a Wear OS watch, like the Samsung Galaxy watch 4/5?

Can it also be accessed in close to real time? I think it requires access to the Sensors API, does react-native-health-connect provide access to the Sensors API?

And can we access the watch sensor data from the React native app running on a phone that is linked to the watch?

Thank you in advance!

Prebuild isn't working

Describe the bug

pre-build isn't working despite doing everything as mentioned in the docs

> npx expo prebuild

CommandError: Package "react-native-health-connect" does not contain a valid config plugin.
Learn more: https://docs.expo.dev/guides/config-plugins/#creating-a-plugin

Cannot use import statement outside a module

Here's my app.json:

{
  "expo": {
    "name": "project",
    "slug": "project",
    "version": "1.0.0",
    "plugins": [
      [
        "expo-build-properties",
        { "android": { "minSdkVersion": 26 } }
      ],
      [
        "react-native-health-connect",
        { "android": { "compileSdkVersion": 33, "targetSdkVersion": 33, "minSdkVersion": 26 } }
      ]
    ],
    "assetBundlePatterns": [
      "**/*"
    ],
    "android": {
      "package": "com.anonymous.project",
      "permissions": [
        "android.permission.health.READ_STEPS",
        "android.permission.health.WRITE_STEPS",
        "android.permission.health.READ_ACTIVE_CALORIES_BURNED"
      ]
    },
    "ios": {
      "bundleIdentifier": "com.anonymous.package"
    },
    "extra": {
      "eas": {
        "projectId": "xxx-xxx"
      }
    }
  }
}

To Reproduce
Steps to reproduce the behavior:

  1. Create a project as specified in the docs
  2. Run npx expo prebuild
  3. See error

Expected behavior
It should have passed without error

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • Health Connect Version: x.x.x
  • React Native Version: 0.71.8
  • New architecture enabled: Don't know

Execution failed for task ':react-native-health-connect:compileDebugKotlin'.

I was attempting to add react-native-health-connect to our React Native app. After adding this library, I changed the minimum SDK to 26 and the compileSdkVersion to 34. Following these changes, the following error appeared:

Screenshot 2024-01-09 at 2 56 00 PM

Steps to reproduce the behavior:

  1. Kotlin version 1.6.10
    2."react-native": "0.71.5",
Screenshot 2024-01-09 at 2 58 07 PM Screenshot 2024-01-09 at 2 58 46 PM Screenshot 2024-01-09 at 2 59 38 PM
  • Health Connect Version: 1.1.0
  • React Native Version: 0.71.5
  • New architecture enabled: Yes/No

Get All vitals

Describe the bug
How can i get last 7 days or 30 days or 6 months individual day steps count calories count heart rate ...etc

Its not a bug need to get some informations

Environment:
-react-native-health-connect": "^1.1.0"

  • React Native Version: 0.72.1
  • New architecture enabled: No

Improvement Suggestions

First of all, thank you very much for this library. Awesome work, clean code!

I found some minor things while using it since yesterday:

Documentation <-> Readme

Readme: yarn add react-native-health-connect@alpha
Doc: yarn add react-native-health-connect (+ alpha note missing)

Documentation Requirements

I also had to upgrade ext.kotlinVersion = "1.8.0"

Health Connect alpha10 migration

Some major things changed in alpha10

Documentation and code changes are required to comply with these

Store redirection / Permission Revoked

  • If Health Connect is not installed users might want to open the market -
  • If the permissions have been revoked twice, users might want to open the Health Connect App

maybe there should be code examples in the doc. I wouldn't implement it in the code (neither automatically nor as and optional param since it's out of scope).

Get Permissions API

Since users can revoke access using the Health Connect App the SDK provides a function to get the current permissions (https://developer.android.com/guide/health-and-fitness/health-connect/get-started#step_4_request_permissions_from_the_user). As of now I'm just creating a useless request and using the exception response to tell if the access has been revoked.

--

I'm not that familiar with Kotlin but let me know if I can help with something.
Also, these are just suggestions/thoughts.

This issue can be closed at any time :)

Can't fetch inserted record

Hi , i can't fetch the record about the "ActiveCaloriesBurned" , tried checking permission and extending the time of the filter with no success

here is the code :

import { PermissionsAndroid, Text } from 'react-native';
import {
  initialize,
  requestPermission,
  readRecords,
  insertRecords,
  readRecord,
  getGrantedPermissions,
} from 'react-native-health-connect';

const HealthDataComponent = () => {
  useEffect(() => {
    readSampleData();
  }, []);

  return (
    <Text>
      This is a component that will read and insert health data from the Health app
    </Text>
  );
};

const requestWritePermission = async () => {
  try {
    const granted = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.WRITE_ACTIVE_CALORIES_BURNED,
      PermissionsAndroid.PERMISSIONS.READ_ACTIVE_CALORIES_BURNED,
    ]);

    if (
      granted[PermissionsAndroid.PERMISSIONS.WRITE_ACTIVE_CALORIES_BURNED] ===
        PermissionsAndroid.RESULTS.GRANTED &&
      granted[PermissionsAndroid.PERMISSIONS.READ_ACTIVE_CALORIES_BURNED] ===
        PermissionsAndroid.RESULTS.GRANTED
    ) {
      // Both permissions granted, you can now call insertSampleData
      insertSampleData();
    } else {
      // Handle permission denied
    }
  } catch (err) {
console.warn(err);
  }
};


export const readSampleData = async () => {
  // Initialize the client
  const isInitialized = await initialize();

  // Request permissions
  const grantedPermissions = await requestPermission([
    { accessType: 'read', recordType: 'ActiveCaloriesBurned' },
    { accessType: 'read', recordType: 'HeartRate' },
    { accessType: 'read', recordType: 'Steps' },
  ]).then(() => {
    const readGrantedPermissions = () => {
      getGrantedPermissions().then((permissions) => {
        console.log('Granted permissions ', { permissions });
      });
    };
    readGrantedPermissions();
  });

  try {
    const result = await readRecords('ActiveCaloriesBurned', {
      timeRangeFilter: {
        operator: 'between',
        startTime: '2021-01-09T12:00:00.405Z',
        endTime: '2023-01-09T23:53:15.405Z',
      },
    });

    console.log('Retrieved records: ', JSON.stringify({ result }, null, 2));
  } catch (error) {
    console.error('Error reading records: ', error);
  }
};


const insertSampleData = () => {
  insertRecords([
    {
      recordType: 'ActiveCaloriesBurned',
      energy: { unit: 'kilocalories', value: 10000 },
      startTime: '2023-01-09T10:00:00.405Z',
      endTime: '2023-01-09T11:53:15.405Z',
    },
    {
      recordType: 'ActiveCaloriesBurned',
      energy: { unit: 'kilocalories', value: 15000 },
      startTime: '2023-01-09T12:00:00.405Z',
      endTime: '2023-01-09T23:53:15.405Z',
    },
  ]).then((ids) => {
    console.log('Records inserted ', { ids }); 
  });
};

export { HealthDataComponent, insertSampleData };

here is the console.log ()

 LOG  Records inserted  {"ids": ["1473e5bf-4b4e-4b6d-bbbe-d2e6c1b301c4", "eed57d89-da43-4dc1-a44c-5b152bb0fe44"]}
 LOG  Granted permissions  {"permissions": [{"accessType": "write", "recordType": "ActiveCaloriesBurned"}, {"accessType": "read", "recordType": "ActiveCaloriesBurned"}, {"accessType": "write", "recordType": "HeartRate"}, {"accessType": "read", "recordType": "HeartRate"}, {"accessType": "write", "recordType": "Steps"}, {"accessType": "read", "recordType": "Steps"}]}
 LOG  Retrieved records:  {
  "result": []
}

the methods are the ones taken from the documetation... so i am a little bit in a roadblock

What am i doing wrong ?

[Error: Mass is not valid]

I'm trying to add a complete recipe macros to Nutrition section.

{
"dietaryFiber": {"unit": "grams", "value": 13}, "endTime": "2024-01-23T08:18:03.000Z", 
"energy": {"unit": "kilocalories", "value": 760},
 "mealType": 1, 
"protein": {"unit": "grams", "value": 38},
 "recordType": "Nutrition", 
"saturatedFat": {"unit": "grams", "value": 7}, 
"sodium": {"unit": "grams", "value": 1},
 "startTime": "2024-01-23T08:18:00.000Z",
 "sugar": {"unit": "grams", "value": 39}, 
"totalCarbohydrate": {"unit": "grams", "value": 77},
 "totalFat": {"unit": "grams", "value": 34}
}

This is the complete record object. Typescript not complaining and everything seems fine but I'm getting this error.

Any ideas?

Permission issue

Describe the bug

android.permission.health.WRITE_ACTIVE_CALORIES_BURNED,android.permission.health.READ_ACTIVE_CALORIES_BURNED added to android manifest
added these two permission but request sample permission and granted permissions getting empty array
{"result": true}
LOG SDK is available
LOG Granted permissions on request {"permissions": []}
LOG Granted permissions {"permissions": []}

To Reproduce

Possible Unhandled Promise Rejection (id: 0):
Object {
"code": "PERMISSION_ERROR",
"message": "[android.permission.health.WRITE_ACTIVE_CALORIES_BURNED] is not declared!",
"nativeStackAndroid": Array [],
"userInfo": null,
}

Expected behavior
I want to get all values like steps calories and vitals Please help me one this

Environment:
"react": "18.2.0",
"react-native": "0.72.1",
"react-native-health-connect": "^1.0.4"

  • New architecture enabled: Yes

Nutrition Record: asking for permission and reading

I can't tell if I missed something, but when trying to ask for permission (using requestPermission) I couldn't find a record type that corresponds to Nutrition. I checked in src/types/records.types.ts for type HealthConnectRecord and Nutrition wasn't listed there.
Same thing with calling readRecords (using readRecords).

Is it actually not supported, or if it is, how do I ask for permission and read nutrition?

Crash issue in Android 13 devices

Describe the bug

When i can openHealthConnectSettings this method app crashed in android 13

To Reproduce
Steps to reproduce the behavior:

Expected behavior
Need to open Health connect page

Screenshots
healthconnectissue

Environment:

  • "react-native-health-connect": "^1.1.0"
  • "react-native": "0.70.6"
  • New architecture enabled: No

insertRecords throws ' Error: text ' for every recordType

Describe the bug
insertRecords throws an error for everyrecortType:

error insert:  Error: text
    at Object.promiseMethodWrapper [as insertRecords] (NativeModules.js:106:51)
    at insertRecords (index.tsx:131:24)
    at onPress (HealthConnectTest.js:82:24)
    at Pressability._performTransitionSideEffects (Pressability.js:756:11)
    at Pressability._receiveSignal (Pressability.js:693:12)
    at onResponderRelease (Pressability.js:524:14)
    at Object.invokeGuardedCallbackProd (ReactNativeRenderer-dev.js:107:10)
    at invokeGuardedCallback (ReactNativeRenderer-dev.js:340:31)
    at invokeGuardedCallbackAndCatchFirstError (ReactNativeRenderer-dev.js:364:25)
    at executeDispatch (ReactNativeRenderer-dev.js:466:3)

To Reproduce
Steps to reproduce the behavior:
After initialization, trigger below code:

insertRecords([
        {
          recordType: 'Hydration',
          volume: {unit: 'milliliters', value: 250},
        },
      ])
        .then(value => console.log(value))
        .catch(e => console.log('error insert: ', e));

Expected behavior
Record should be added and then retrieved successfully

Environment:

  • Health Connect Version: 1.0.2
  • React Native Version: 0.69.7
  • New architecture enabled: No

lateinit property requestPermission has not been initialized

Describe the bug
I've followed the exact installation in your documentation on how to use it with expo.
I'm using an expo dev build with config plugin.

Tried to run the app on Android 13 and 10, both encountered the same error.
Downgraded to version 1.2.3 and it is now working.

However, I'd like to report the issue so I can upgrade to the latest version.

Here's the error log:

Your app just crashed. See the error below. kotlin.UninitializedPropertyAccessException: lateinit property requestPermission has not been initialized dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate.launch(HealthConnectPermissionDelegate.kt:32) dev.matinzd.healthconnect.HealthConnectManager$requestPermission$1$1.invokeSuspend(HealthConnectManager.kt:64) kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108) kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115) kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103) kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584) kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793) kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697) kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)

Screenshot 2024-03-06 at 7 09 17 PM

Environment:

  • Health Connect Version: 2.0.1
  • React Native Version: 0.73.5

Can't import HealthConnectPermissionDelegate into Java code

Describe the bug
I'm trying to add the code for v2 to my main activity, but my project is in Java not Kotlin. The dev.matinzd.healthconnect.permissions project doesn't appear in Android Studio (I have Kotlin-android plugin set up), and I can't import the HealthConnectPermissionDelegate class.

To Reproduce
Steps to reproduce the behavior:
Create fresh React Native project in version that uses Java. Install v2 of this library. Note that the code doesn't appear in Android Studio and you can't import the classes.

Expected behavior
I can import the class and use the example in the readme but in Java.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • Health Connect Version: 2.0.0
  • React Native Version: 0.72.6
  • New architecture enabled: Yes?

This release includes permissions that haven't been declared in Play Console

Describe the bug
This release includes permissions that haven't been declared in Play Console. Go to Sensitive app permissions to update your permission declarations. Learn more

Error
You need approval to use the following Health Connect permissions in your app:
android.permission.health.READ_ACTIVE_CALORIES_BURNED
android.permission.health.READ_HEART_RATE
android.permission.health.READ_STEPS
android.permission.health.READ_DISTANCE
android.permission.health.READ_FLOORS_CLIMBED

To Reproduce
While uploading app bundle to play store

Expected behavior
A clear and concise description of what you expected to happen.

Environment:

  • Health Connect Version: 1.1.0
  • React Native Version: 0.72.4
  • New architecture enabled: No

Sleep recordType value mismatch between methods

Describe the bug
requestPermission() requires permission name as SleepSession and getGrantedPermissions() returns Sleep
To Reproduce
Steps to reproduce the behavior:

  1. Trigger requestPermission([{accessType: 'read', recordType: 'SleepSession'}])
  2. Trigger getGrantedPermissions()
  3. See permissions array from getGrantedPermissions

Expected behavior
recordType should match on both methods

Screenshots
image

Environment:

  • Health Connect Version: 1.2.3
  • React Native Version: 0.73.1
  • New architecture enabled: Yes

readRecords returning only 1 record and aggregateRecord dont match with it

Describe the bug

  1. readRecords doesnt match the data returned by aggregateRecord(0)
  2. readRecords returns only 1 record regardless of the date range. Is it relared to the HealthConnect or my app installation/permission date?

Wearable: Samsung Watch 3
App: Samsung Health + Health Connect(latest)

To Reproduce
Steps to reproduce the behavior:

readRecords('Steps', {
  timeRangeFilter: {
    operator: 'between',
    startTime: '2023-04-01T04:00:00Z',
    endTime: new Date().toISOString(),
  },
})
  .then(value => console.log(value))
  .catch(e => console.log(e));

aggregateRecord({
  recordType: 'Steps',
  timeRangeFilter: {
    operator: 'between',
    startTime: new Date(
      new Date().getTime() - 7 * 24 * 60 * 60 * 1000, // 7 days
    ).toISOString(),
    endTime: new Date().toISOString(),
  },
}).then(result => {
  console.log(result);
});

Expected behavior

  • readRecords should return all records for entered date range
  • The total steps should be the same on both methods

Screenshots
image
Environment:

  • Health Connect Version: 1.0.1
  • React Native Version: 0.69.7
  • New architecture enabled: No

requestPermission on Android 14

Describe the bug
Calling requestPermission will lead into an error: "No Activity found to handle Intent { act=androidx.activity.result.contract.action.REQUEST_PERMISSIONS (has extras) }

However, on Android 13 the issue does not exist.

To Reproduce
When trying to request permissions the application crashes with the error (see above)

Expected behavior
HealthConnect shows the permission selection (Same behavior as on Android 13).

Screenshots

Environment:

  • Health Connect Version: 1.2.1
  • React Native Version: 0.72.6
  • Expo Version: 49.0.15

Not able to readRecords

Describe the bug
I've managed to initialize the SDK on my phone, and I've granted all the necessary permissions. However, when I attempt to retrieve records from the SDK, it consistently returns an error message stating, "Health Connect client is not initialized."

Additional info

  • I have properly initialized the SDK, and when I checked it using the "initialize()" method, it returned a true value.
  • I've also examined the SDK status with "getSdkStatus()" and it's returning "3."

Code Screenshots
Screenshot 2023-09-14 at 5 55 55 PM

Error Screenshots
Screenshot 2023-09-14 at 5 52 58 PM

Environment:

  • Health Connect Version: 1.2.0
  • React Native Version: 0.68.7
  • New architecture enabled: Yes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.