React Native Framework Wrapper
Validic_react-native-1.4.5
Legacy (v1) vs Inform (v2)
The same Validic Mobile SDKs are used by both Legacy (v1) and Inform (v2) API customers. To make the documentation easier to access, the Mobile Getting Started Guides and class documentation are hosted on our Inform (v2) documentation site.
The API documentation, however, is different between Legacy (v1) and Inform (v2). If you are an Inform (v2) API customer, you must use the Inform API documentation.
If you are a Legacy (v1) API customer, be sure to go back to the Legacy API documentation.
This project integrates Healthkit, Google Fit, and Samsung Health with the Validic Mobile Aggregator to passively collect data on behalf of an end user.
Are you already using our React Native wrapper? If so, are you interested in beta testing our React Native Bluetooth framework? Reach out to our customer support team or your Validic Client Success Executive if you'd like to learn more about our beta Bluetooth support for React Native!
Requirements
This plugin provides a bridge between a React Native based application and native Validic Mobile libraries. The native libraries are required for use of this plugin.
Plugin requirements:
- React Native 0.62.3 and above.
- Specific supported phones, peripherals, and/or operating system versions are documented as part of the native libraries.
Prerequisites
In order to use the Validic Mobile Library, you will need a valid organization id and valid user credentials.
If you do not already have an organization id, you will need to first apply for one.
After your organization is set up, you will need a Validic user id and access token.
Validic user can be provisioned using the Validic API, documentation is available for both Legacy API (V1) and Inform API (V2) APIs. The credentials needed are a Validic user ID, an organization ID and a user access token. The user access token value you provide to the SDK is the "user access token" value if you use the Legacy (V1) API. The user access token value you provide to the SDK is the "mobile token" value if you use the Inform (V2) API.
Add Plugin to React Native Project
Install
To get started, download the React Native framework from the Validic Mobile portal. Install the framework:
$ npm install <path to react-native-validic-session-1.4.5.tgz> --save
or use yarn
$ yarn add <path to react-native-validic-session-1.4.5.tgz>
Link framework
Automatic
react-native link <path to react-native-validic-session-1.4.5.tgz>
For iOS users using Pods
You still need to run pod install
after running the above link command inside your IOS
folder.
Manual
iOS (via CocoaPods) RN >= 60
Add the following lines to your build targets in your Podfile
pod 'React', :path => '../node_modules/react-native'
pod 'RNValidicSession', :path= => '../node_modules/react-native-validic-session'
Then run pod install
iOS (without CocoaPods)
In XCode, in the project navigator:
- Right click Libraries
- Add Files to [your project's name]
- Go to
node_modules/react-native-validic-session/ios
- Add the file
RNValidicHealthkit.xcodeproj
In XCode, in the project navigator, select your project.
- Add the
libRNValidicHealthkit.a
from the RNValidicHealthkit project to your project's Build Phases ➜ Link Binary With Libraries - Click
.xcodeproj
file you added before in the project navigator and go the Build Settings tab. Make sure All is toggled on (instead of Basic). - Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React
and$(SRCROOT)/../../React
- Mark both as recursive (should be OK by default).
In the General tab there will be a panel at the bottom of the screen labeled "Embedded Binaries". You should see the frameworks added here.
Next copy 'copy-validicmobile.rb' to the ios
folder of your project.
Go to the build settings of your target. In the "Build Phases" tab add a new build phase by clicking the plus button at the top and selecting "New Run Script Phase".
In the new phase's text area paste in ruby copy-validicmobile.rb
.
Android
- Open up
android/app/src/main/java/[...]/MainApplication.java
- Add
import com.validic.mobile.rn.session.RNValidicMobileSessionPackage;
to the imports at the top of the file - Add
new RNValidicMobileSessionPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-validic-session' project(':react-native-validic-session').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-validic-session/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:implementation project(':react-native-validic-session')
Import
import ValidicSession from '<path to react-native-validic-session-1.4.5.tgz>';
Session
Record types
The Validic Mobile library supports the following record types:
-
Biometrics
- comprised of a user’s biometric health data such as blood pressure, cholesterol, heart rate, and blood and hormone levels. -
Diabetes
- comprised of a user’s blood glucose and hormone levels related to diabetes treatment and management. -
Fitness
- comprised of a user’s activities that are undertaken with the express purpose of exercising. These activities have a defined duration (time, distance, elevation, etc.) -
Nutrition
- comprised of a user’s activities related to calorie intake and consumption and nutritional information (such as fat, protein, carbohydrates, sodium, etc.) -
Routine
- comprised of a user’s activities that occur regularly throughout the day, without the specific goal of exercise, for example calories burned and consumed, steps taken, stairs climbed. These activities are aggregated throughout the day. -
Sleep
- comprised of a user’s measurements related to the length of time spent in various sleep cycles, as well as number of times awakened during the night. -
Weight
- comprised of a user’s weight and body mass.
Record Identifiers
The Validic Mobile SDK uses log_id
(for the Inform/V2 API) or activity_id
(for the Legacy/V1 API) as the unique identifier for a given record. These IDs are created by the mobile SDK before submission to the server.
The Validic server also assigns an id
(for the Inform/V2 API) or _id
(for the Legacy/V1 API) for each unique record. It is recommended to use the server-side id
/ _id
to identify and/or de-duplicate records post-submission.
Provision a user
The Validic Mobile library requires a Validic user. A Validic user can be provisioned using the Validic API. The library requires a Validic user ID, user access token and organization ID. It is recommended to provision the user on your server, the mobile app could then authenticate to the server and retrieve the Validic credentials.
Manage a session
The ValidicSession
persists a user across the sdk and all pending record uploads. This data is persisted between
app launches but is deleted if the ValidicSession.endSession
function is called.
A new Session is started by passing previously provisioned Validic user credentials to the startSession
function.
ValidicSession.startSession({user_id:USER_ID, org_id: ORGANIZATION_ID, user_token: USER_ACCESS_TOKEN});
The supplied credentials are validated when the session is created. Records will fail to upload if invalid credentials have been provided. Credentials are stored persistently. To change credentials, call:
ValidicSession.endSession();
or uninstall the app. When a new session is created, pending record uploads and subscriptions are reset. For this reason, a new session should only be created if a session it not already active.
The app can be informed of record upload success and failure by registering callbacks using:
Handle events
Listeners can be added to listen for success or failure of records submitted to the Validic Api. Registration of listeners is typically done during component initialization to catch events for record uploads which may occur upon app restart.
ValidicSession.eventEmitter.addListener('validic:session:onsuccess', (record)=>{
// the record was successfully uploaded to validic servers
console.log("Successfully got record" + JSON.stringify(record));
});
ValidicSession.eventEmitter.addListener('validic:session:onerror', (error, record)=>{
// an error was returned while submitting the record
console.error("Got error: "+error + " for record: " + record.activity_id);
});
Example
The following example starts a session if a session is not already active and registers session listeners.
componentDidMount(){
ValidicSession.eventEmitter.addListener('validic:session:onsuccess', (record)=>{
// the record was successfully uploaded to validic servers
console.log("Successfully got record" + JSON.stringify(record));
});
ValidicSession.eventEmitter.addListener('validic:session:onerror', (error, record)=>{
// an error was returned while submitting the record
console.error("Got error: "+error + " for record: " + record.activity_id);
});
var user = {
user_id: "replace with userid",
user_token : "replace with access token",
org_id : "replace with organization id"
};
// check if a persistent user already exists
ValidicSession.getUser((response)=>{
//if not, start a new session
if(response.user == null){
ValidicSession.startSession(user);
}
});
}
...
//remove event listeners when the component is going to be unmounted
componentWillUnmount(){
ValidicSession.eventEmitter.removeAllListeners('validic:session:onsuccess');
ValidicSession.eventEmitter.removeAllListeners('validic:session:onerror');
}
Logging
Logging for the Native sdk can be enabled or disabled at runtime.
import {ValidicLog} from 'react-native-validic-session';
// to enable
ValidicLog.enable();
// to disable
ValidicLog.disable();
Healthkit
This project integrates Healthkit with the Validic Mobile Aggregator to passively collect Apple Health data on behalf of an end user.
Install
To get started, first install the framework
$ npm install react-native-validic-aggregator-ios --save`
or use yarn
$ yarn add react-native-validic-aggregator-ios`
Link framework
Automatic
react-native link react-native-validic-aggregator-ios
For iOS users using Pods
You still need to run pod install
after running the above link command inside your IOS
folder.
Manual
iOS (via CocoaPods) RN >= 60
Add the following lines to your build targets in your Podfile
pod 'React', :path => '../node_modules/react-native'
pod 'RNValidicHealthkit', :path => '../node_modules/react-native-validic-aggregator-ios'
pod 'RNValidicSession', :path= => '../node_modules/react-native-validic-session'
Then run pod install
iOS (without CocoaPods)
In XCode, in the project navigator:
- Right click Libraries
- Add Files to [your project's name]
- Go to
node_modules/react-native-validic-aggregator-ios/ios
- Add the file
RNValidicHealthkit.xcodeproj
In XCode, in the project navigator, select your project.
- Add the
libRNValidicHealthkit.a
from the RNValidicHealthkit project to your project's Build Phases ➜ Link Binary With Libraries - Click
.xcodeproj
file you added before in the project navigator and go the Build Settings tab. Make sure All is toggled on (instead of Basic). - Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React
and$(SRCROOT)/../../React
- Mark both as recursive (should be OK by default).
In the General tab there will be a panel at the bottom of the screen labeled "Embedded Binaries". You should see the frameworks added here.
Next copy 'copy-validicmobile.rb' to the ios
folder of your project.
Go to the build settings of your target. In the "Build Phases" tab add a new build phase by clicking the plus button at the top and selecting "New Run Script Phase".
In the new phase's text area paste in ruby copy-validicmobile.rb
.
Enable Healthkit
To enable use of HealthKit in the app, within the build settings of your target, select the 'Signing & Capabilities' tab and click '+ Capability'. Choose 'HealthKit' and make sure 'Background Delivery' is checked as well.

HealthKit entitlements
If Healthkit is not enabled, an error is reported in the console log on app launch but will not report an error during build.
Permission Usage Descriptions
Usage descriptions have to be declared in project's Info.plist
for permissions of the Camera, Bluetooth and to access and update Healthkit data.
- HEALTH_SHARE_USAGE_DESCRIPTION for NSHealthShareUsageDescription
- HEALTH_UPDATE_USAGE_DESCRIPTION for NSHealthUpdateUsageDescription
Import
import ValidicHealthKit from 'react-native-validic-aggregator-ios';
Manage subscriptions
To subscribe to Healthkit sample types:
Set subscriptions
Calling ValidicHealthkit.setSubscriptions(subscriptions)
will overwrite any existing subscriptions so it is important to always pass all of the subscriptions desired each time the method is called.
To get a list of the currently subscribed data types use the method described in Current subscriptions
ValidicHealthKit.setSubscriptions([ValidicHealthKit.SampleTypes.HKQuantityTypeIdentifierStepCount]);
The function accepts an array of strings mapping to Healthkit sample types.
Get current subscriptions
To retrieve the list of Sample Types currently being observed
ValidicHealthKit.getCurrentSubscriptions((subscriptions)=>{
if(!subscriptions.includes(ValidicHealthKit.SampleTypes.HKQuantityTypeIdentifierStepCount)){
subscriptions.push(ValidicHealthKit.SampleTypes.HKQuantityTypeIdentifierStepCount);
ValidicHealthKit.setSubscriptions(subscriptions);
}
});
Handle events
An event will be passed to the ValidicHealthKit.eventEmitter
every time Healthkit processes a record type in the background.
The event will contain the count and type of record processed from Healthkit.
ValidicHealthKit.eventEmitter.addListener('validic:healthkit:onrecords', (summary){
console.log(summary.type) //type of record that corresponds to ValidicHealthKit.SummaryType
console.log(summary.count) // count of how many records of the corresponding Summary Type were processed by Healthkit
})
Events should be removed as soon as they are no longer needed or the component observing them will be umounted
componentWillUnmount(){
ValidicHealthKit.eventEmitter.removeAllListeners('validic:healthkit:onrecords');
}
Retrieve data continuously
To properly enable the continuous delivery of data in the background and foreground, the subscription observers need to be recreated immediately when the app is launched from a suspended or terminated state. To do this, you need to call ValidicHealthKit.observeCurrentSubscriptions()
whenever the app is launched or foregrounded, such as in componentDidMount()
in the app's root component. Example:
componentDidMount() {
if (Platform.OS === 'ios') {
ValidicHealthKit.observeCurrentSubscriptions();
}
}
Note: Calling Session.getInstance().endSession()
will remove all HealthKit subscriptions and stop listening for new data.
Google Fit
This project integrates Google Fit with the Validic Mobile Aggregator to passively collect data on behalf of an end user. Validic ensures that our Mobile SDK makes use of the minimal scopes needed for our supported data types. Additionally, when using Google Fit version com.google.android.gms:play-services-fitness:19.0.0
or lower, Validic does not request or use any scopes indicated as sensitive or restricted by Google.
With the upcoming Google Fit version com.google.android.gms:play-services-fitness:20.0.0
, all read scopes will be restricted and will require completing Google’s sensitive scope verification or restricted scope verification and security assessment to retrieve data. Please see Google's announcement for further details: https://developers.google.com/fit/improvements
Be aware that Google has an extensive and potentially lengthy verification process. Google manages their own verification process and it is subject to change at any time at their discretion. It is your responsiblity to review, understand, and follow Google's verification process and provide Google with all information they request before sharing your application publicly. Validic does not provide direct support for Google's verification process, however, Google's Verification FAQ is detailed and provides you with the information you'll need to complete the process. See the Customer Requirements section below for highlights on setting up, developing, and verifying for Google Fit.
Customer Requirements
Google Fit is available for Inform (V2) Validic customers. If you are a Legacy customer and are interested in Google Fit, please reach out to your Validic Client Success Manager.
Validic's Google Fit integration works with Google Fit for Android. Google Fit for Android uses Google's OAuth API for accessing user data. There is setup that must occur before you implement Google Fit into your mobile project so that your users can consent to sharing and share their data successfully:
Before you start development, in Google Api Console you must:
- Create Google Services OAuth 2.0 Client IDs
- Verify your domain ownership
- Configure your user consent screen
After completing the above setup, you can start development using the instructions in this tutorial. While you are developing, testing can occur with Google user accounts that are registered to the same domain as the mobile project.
After development and testing are complete and before you launch your app, you will need to submit a request to Google for Oauth API Verification. There are certain instances where this may not be required (see Google's FAQ for details).
Once you submit your verification request, you may be required to provide some or all of the following:
- Application Homepage detailing your use of requested scopes
- Privacy Policy and Terms & Conditions
- Application Demo Video showing the user consent workflow in your app
- Application Name, Logo, and/or other branding elements
Google dictates their own verification process so you may be asked to provide additional information as well. See Veification Requirements for more information. Be sure to respond to Google's requests as quickly as possible to minimize delays in getting your verification approved.
2021 Google Fit Changes
Google announced late in 2020 that they would be changing several scopes and marking a majority of them as "Sensitive" scopes. Requesting access to “Sensitive” scopes requires a more in depth review by the Google Fit team before granting access to end user Google Fit data.
This change is optional now, but will be required starting May 4, 2021. More information about this change can be found here. Changes will be required in the Google Api Console to adjust to the changes in oAuth scopes mentioned in the link/email from Google.
Your app must update to use Google fit dependency version 20.0.0. The Validic SDK added support for this dependency in v1.12.12
release. It is always recommend to update to the latest version of the Validic SDK when updating dependencies.
- Install
$ npm install react-native-validic-aggregator-fit --save
- Mostly automatic installation
$ react-native link react-native-validic-aggregator-fit
Import
import ValidicAggregatorFit from 'react-native-validic-aggregator-fit';
Initialization
ValidicAggregatorFit
will be initialized at app startup and will immediately start listening for
previously subscribed data types. It is recommended that you set a listener on the ValidicAggregatorFit
during your componentDidMount()
method
componentDidMount() {
ValidicAggregatorFit.eventEmitter.addListener('validic:fit:onrecords',(summary)=>{
console.log("Proccessed Google Fit Data");
console.log(summary);
});
ValidicAggregatorFit.eventEmitter.addListener('validic:fit:onerror', (callback)=>{
console.warn(callback.error);
});
Make sure to unsubscribe from events during componentWillUnmount()
.
componentWillUnmount() {
ValidicAggregatorFit.eventEmitter.removeAllListeners('validic:fit:onrecords');
ValidicAggregatorFit.eventEmitter.removeAllListeners('validic:fit:onerror');
Request permissions
Before collecting any data from Google Fit, a Google Account must be associated with the ValidicAggregatorFit
, and the end user must authorize the app to collect data on their behalf.
Get previously granted permissions
To check if permissions have already been granted the hasDataAccess(dataTypes)
method can be used
import { Platform, PermissionsAndroid } from 'react-native';
let permissions = await ValidicAggregatorFit.requestPermissions([ValidicAggregatorFit.DataTypeStepCount])
if(permissions[ValidicAggregatorFit.DataTypeStepCount] == true){
//subscribe
}
The promise returned from hasDataAccess(dataTypes)
associates a DataType
with true, if a valid Google account exists and permission has previsouly been granted, or false otherwise.
Request new permissions
To request permission from the end user to authorize data collection the requestPermissions(dataType)
function can be used to authorize your application
let permissions = await ValidicAggregatorFit.requestPermissions([ValidicAggregatorFit.DataTypeStepCount])
if(permissions[ValidicAggregatorFit.DataTypeStepCount] == true){
//subscribe
}
Android 10
For the Android client Apps that target API 29 the permission below is required in the AndroidManifest.xml. The Validic SDK will add this permission to its manifest so that it will be merged with the client when they add our library to their application.
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
This permission is required to subscribe to the following data types:
- com.google.step_count.delta
- com.google.step_count.cumulative
- com.google.step_count.cadence
- com.google.activity.segment
- com.google.activity.exercise
For apps targeting Android 10, this permission must be requested from the user at runtime
var granted = await PermissionsAndroid.check(
'android.permission.ACTIVITY_RECOGNITION',
)
if (!granted){
granted = await PermissionsAndroid.request(
'android.permission.ACTIVITY_RECOGNITION',
{
'title': 'Example App',
'message': 'Example App access to your location '
}
)
}
if(!granted){
console.log("Activity Permission not granted")
}
}
Manage subscriptions
After Permissions have been granted for a DataType
the ValidicAggregatorFit
can be used to add subscriptions to data change events from Google Fit.
Data will automatically will queued for submission to the Validic API when internet is available on the device
ValidicAggregatorFit.subscribe([ValidicAggregatorFit.DataTypeStepCount]);
To unregister from receiving data update events use the ValidicAggregatorFit
to unsubscribe
ValidicAggregatorFit.unsubscribe(ValidicAggregatorFit.DataTypeStepCount);
Get a list of currently subscribed DataType
s
let subscriptions = await ValidicAggregatorFit.currentSubscriptions()
Get currently supported DataTypes
Available datatypes can be referenced from the ValidicAggregatorFit
.datatype
- DataTypeStepCount
- DataTypeWeight
- DataTypeHeartRate
- DataTypeCaloriesExpended
- DataTypeMoveMinutes
- DataTypeDistance
- DataTypeNutrition
Records collected are automatically submitted to the Validic Inform API and a summary of records processed will be sent as an event named validic:fit:onrecords
.
For an example of setting a listener see Initialization
Fetch Historical Summary data
Depending on your use case, it might be beneficial to capture an end-user's Summary data from previous days that has been stored in Google Fit. To fetch up to 180 days of previous summary data for a user use the fetchHistory()
function.
ValidicAggregatorFit.fetchHistory
Please note that this is a computationally expensive task that requires fetching data from google. Only a single call to this function can take action and consecutive calls to this method will be dropped until the first call has completed. After all processing has been completed a summary event will be emitted to any listeners registered to the eventEmitter for the validic:fit:onrecords
event. If any error occurs, an error event will be emitted to any listeners registerred to the validic:fit:onerror
event.
For an example of setting a listener see Initialization
Logout
To remove all subscriptions and log an end user out simply call
ValidicAggregatorFit.disconnect()
Samsung Health
This project integrates Samsung Health with the Validic Mobile Aggregator to passively collect data on behalf of an end user.
Approval Required
The Samsung Health integration requires pre-approval for Samsung's Device SDK.
Currently, Samsung is going through an update to better support their partners and, for that reason, they are not accepting applications for the Partner Apps Program. We will keep this section up to date as we hear any updates from the Samsung team.
Install
To get started, install the framework
$ npm install react-native-validic-aggregator-shealth --save
Mostly automatic installation
$ react-native link react-native-validic-aggregator-shealth
Manual installation
Android
- Open up
android/app/src/main/java/[...]/MainApplication.java
- Add
import com.validic.mobile.rn.shealth.RNValidicMobileAggregatorPackage;
to the imports at the top of the file - Add
new RNValidicMobileAggregatorPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-validic-aggregator-shealth' project(':react-native-validic-aggregator-shealth').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-validic-aggregator-shealth/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:compile project(':react-native-validic-aggregator-shealth')
Samsung Health
In order to use Samsung Health with ValidicMobile a valid copy of the Samsung Health SDK must be provided by the developer. This can be downloaded from the SHealth developer portal: Samsung SHealth Developer.
Place the samsung-health-data-v1.5.0.aar
in the same `android/app/libs
of your app. If the folder does not exist, please create it
Developer mode
In order to test, you must enable developer mode in the Samsung Health app on your phone. For instructions on how to enable developer mode please see Samsung's website: https://developer.samsung.com/health/android/data/guide/dev-mode.html
Note: Starting with Samsung Health app version 6.11.0.061 (released August 2020), in order to gain access to Samsung Health data, with or without developer mode enabled, you must first be approved by Samsung and receive a Samsung dev access key. Prior versions of the Samsung Health app do not require the dev access key when the Samsung Health app is in developer mode.
You can learn more about requesting access via Samsung's website here: https://developer.samsung.com/health/android/overview.html#Partner-Apps-Program
Import
import ValidicSHealth from 'react-native-validic-aggregator-shealth';
Manage subscriptions
Configuration
Starting with Android Oreo, background execution limits are imposed on applications in the background and will destroy them after a certain amount of time. To prevent this it is recommended to configure the ValidicSHealth
object with a foreground service notification configuration. This will ensure that results are develivered in near real time.
ValidicSHealth.configure({
notification_id: 1,
notification_title: "title",
notification_clear_text: "Stop", // if set will create a button in the notification that will stop observing data until the next time the app is launched
notification_icon: "ic_launcher.png" // will look resource folders for file named ic_launcher.png
});
Available Data Types
Samsung provides several data types that can be subscribed to for notification when data changes.
The available data types are:
- com.samsung.health.blood_glucose
- com.samsung.health.blood_pressure
- com.samsung.health.body_temperature
- com.samsung.health.caffeine_intake
- com.samsung.health.exercise
- com.samsung.health.food_info
- com.samsung.health.food_intake
- com.samsung.health.hba1c
- com.samsung.health.heart_rate
- com.samsung.health.oxygen_saturation
- com.samsung.health.sleep
- com.samsung.health.sleep_stage
- com.samsung.health.uv_exposure
- com.samsung.health.water_intake
- com.samsung.health.weight
- com.samsung.shealth.step_daily_trend
NOTE: Data types that are going to be used in your application must be added to the AndroidManifest.xml.
android/app/AndroidManifest.xml
<application name="testApp">
<meta-data android:name="com.samsung.android.health.platform_type" android:value="rel"/>
<meta-data android:name="com.samsung.android.health.permission.read" android:value="com.samsung.health.blood_glucose;com.samsung.health.exercise"/>
</application>
Check Read Access for HealthDataTypes
Read access is required to set subscriptions for a dataType.
let results = await ValidicSHealth.hasReadAccess([ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]);
if(results[ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]){
//has access
}else {
//does not have access. Adding a subscription will result in an error being emitted and the subscription removed
}
Request Read Permission for HealthDataTypes
In order to request the end user grant read access to ValidicSHealth
use requestPermissions
let results = await ValidicSHealth.hasReadAccess([ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]);
if(results[ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]){
//has access
}else {
//does not have access.
let results1 = ValidicSHealth.requestPermissions([ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]);
if(results1[ValidicSHealth.requestPermissions[ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]]){
//has access
} else {
//permission was denied
}
}
Request Subscriptions to HealthDataTypes
After read access has been granted for a data type it can be subscribed to for data to automatically be uploaded to the Validic API.
let results = await ValidicSHealth.hasReadAccess([ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]);
if(results[ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]){
ValidicSHealth.requestSubscriptions([ValidicSHealth.HealthDataTypes.DAILY_STEP_COUNT]);
}
If permission has not been granted and a subscription is attempted then an error event will be thrown and the subscription removed.
Please see (Events)[#events] to listen for the error event.
NOTE: Calling ValidicSession.endSession()
will remove all SHealth subscriptions and stop listening for new data.
Fetch historical data
Validic provides the ability to query up to 6 months of data for a subset of data types provided by Samsung Health by querying
an array of ValidicSHealth.HistoricalSetType
Currently 2 historical sets are available
- ValidicSHealth.HistoricalSetType.HistoricalSetTypeFitness - Exercise data
- ValidicSHealth.HistoricalSetType.HistoricalSetTypeRoutine - Step data
ValidicSHealth.fetchHistory([ValidicSHealth.HistoricalSetType.HistoricalSetTypeRoutine]); //fetch last 6 months of walking data
This is will trigger the EVENT_ON_HISTORY_FETCH
event described in the Events section
Handle events
To listen for events from SHealth an eventListener should be added to the native event emitter. It is recommended to do this in your comonents componentDidMount method
ValidicSHealth.eventEmitter.addListener(ValidicSHealth.EventNames.EVENT_ON_PERMISSION_CHANGE, (permissions)=>{
// SHealth permissions have changed
console.log(permissions.accepted) // array of accepted permissions from the user
console.log(permissions.denied) // array of permissions denied by the user
});
ValidicSHealth.eventEmitter.addListener(ValidicSHealth.EventNames.EVENT_ON_ERROR, (error)=>{
// An error has occurred with SHealth
console.error(error);
});
ValidicSHealth.eventEmitter.addListener(ValidicSHealth.EventNames.EVENT_ON_RECORDS,(recordSummary)=>{
// Validic has gathered records because of a data type subscription change
console.log(recordSummary) // summary of how many records were collected by the subscriptions keyed by the `ValidicSHealth.SummaryTypes`
});
ValidicSHealth.eventEmitter.addListener(ValidicSHealth.EventNames.EVENT_ON_HISTORY_FETCH, (historySummary)=>{
// Validic data has pulled 6 months of records from SHealth
console.log(historySummary) // summary of how many records were collected by the subscriptions keyed by the `ValidicSHealth.HistoricalSetTypes`
});
Events should be removed when they are no longer necessary or when the component listening will be unmounted
componentWillUnmount(){
ValidicSHealth.eventEmitter.removeAllListeners(ValidicSHealth.EventNames.EVENT_ON_PERMISSION_CHANGE);
ValidicSHealth.eventEmitter.removeAllListeners(ValidicSHealth.EventNames.EVENT_ON_RECORDS);
ValidicSHealth.eventEmitter.removeAllListeners(ValidicSHealth.EventNames.EVENT_ON_HISTORY_FETCH);
ValidicSHealth.eventEmitter.removeAllListeners(ValidicSHealth.EventNames.EVENT_ON_ERROR);
}
Updated about 1 month ago