React Native Framework Wrapper
Validic_react-native-1.5.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 accessing 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 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.
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
Usage
import { ValidicHealthKit } from 'react-native-validic-aggregator-ios';
Checking if HealthKit is available
Not all iOS devices support HealthKit (e.g. iPads running iOS 16 or lower and other platforms such as Android). To check if HealthKit is available, Apple provides an API: [HKHealthStore isHealthDataAvailable]
. For convenience, Validic provides a React Native method to check this value: ValidicHealthKit.isHealthDataAvailable()
. It returns a Promise that resolves to the value returned [HKHealthStore isHealthDataAvailable]
and false
for every other platform.
ValidicHealthKit.isHealthDataAvailable()
.then(healthDataIsAvailable => {
if (healthDataIsAvailable) {
console.log('HealthKit is available!');
}
else {
console.log('HealthKit is not available :(');
}
});
// async/await
try {
const available = await ValidicHealthKit.isHealthDataAvailable();
console.log("HealthKit is available:" + available);
} catch(error) {
console.error(error);
}
Subscriptions
To subscribe to HealthKit sample types:
Current Subscriptions
To retrieve the list of Sample Types currently being observed
ValidicHealthKit.getCurrentSubscriptions()
.then(subscriptions => {
console.log(JSON.strigify(subscriptions)); // ["HKQuantityTypeIdentifierStepCount"]
})
.catch(error => console.error(error));
// async/await
try {
const subscriptions = await ValidicHealthKit.getCurrentSubscriptions();
console.log(JSON.stringify(subscriptions)); // ["HKQuantityTypeIdentifierStepCount"]
} catch (e) {
console.error(e);
}
Set Subscriptions
Calling ValidicHealthKit.setSubscriptions(subscriptions)
will replace any existing subscriptions, so it is important to always pass all of the subscriptions desired each time the method is called. The function accepts an array of strings mapping to HealthKit sample type identifiers (e.g. "HKQuantityTypeIdentifierStepCount"
) and returns a Promise that resolves after permissions have been granted by the end user and the subscriptions have been set up.
To get a list of the currently subscribed data types use the method described in Current subscriptions
ValidicHealthKit.setSubscriptions([ValidicHealthKit.SampleTypes.HKQuantityTypeIdentifierStepCount])
.then(() => {
console.log("Subscribed to Steps");
})
.catch(error => console.error(error));
// async/await
try{
await ValidicHealthKit.setSubscriptions([ValidicHealthKit.SampleTypes.HKQuantityTypeIdentifierStepCount]);
console.log("Subscribed to steps");
} catch (e) {
console.error(e);
}
Fetching historical data
To fetch historical Summary
data use the fetchHistory
function. The maximum amount of data that can be fetched is 180 days in the past.
let start = new Date()
let end = new Date()
start.setDate(end.getDate()-29)
ValidicHealthKit.fetchHistory({
historicalSets: [ValidicHealthKit.HistoricalSets.HistoricalSetRoutine],
from: start.toISOString(),
to: end.toISOString()
})
.then(summary => {
console.log(JSON.stringify(summary));
})
.catch(error => {
console.error(error);
});
// async/await
try {
const summary = await ValidicHealthKit.fetchHistory({
historicalSets: [ValidicHealthKit.HistoricalSets.HistoricalSetRoutine],
from: start.toISOString(),
to: end.toISOString()
});
console.log(JSON.stringify(summary));
} catch (e) {
console.error(e);
}
Events
An event will be passed to ValidicHealthKitEvents
every time HealthKit processes new records. The event contains a summary of the number of records collected per SummaryType
.
ValidicHealthKitEvents.addListener('validic:healthkit:onrecords', (summary) => {
console.log(JSON.stringify(summary)); // {"biometrics":1, "summary":1}
});
Listeners should be removed as soon as they are no longer needed, or when the component observing them will be unmounted.
componentWillUnmount() {
ValidicHealthKitEvents.removeAllListeners('validic:healthkit:onrecords');
}
Google Fit
Google Fit
As of May 1, 2024 Google has decided to stop accepting new applications for the Google Fit Android SDKs that are used in the Validic Mobile Google Fit integration.
As of this update, the Fit Android SDKs are deprecated and will be officially sunset on June 30, 2025. You can find the latest information from Google at any time by visiting their help pages.
During this time, clients who have already been approved by Google to use the Google Fit Android SDKs may continue to use the Google Fit integration.
Validic is currently working on a beta Mobile SDK integration to Android Health Connect, which can be used to retrieve Google Fit data. Please stay tuned for updates when this integration is available for testing.
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.
As of Google Fit version com.google.android.gms:play-services-fitness:20.0.0
, all read scopes are restricted and 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
- 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);
}
Bluetooth
Are you already using our React Native wrapper? If so, are you interested in accessing 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 Bluetooth support for React Native!
This project integrates Bluetooth capabilities with the Validic Mobile Full SDK to actively and passively collect data from supported Bluetooth Low Energy (LE) devices on behalf of an end user.
Install
To get started, install the framework
npm install react-native-validic-ble-<version>.tgz
or
yarn add react-native-validic-ble-<version>.tgz
Usage
import { ValidicBluetooth } from "react-native-validic-ble";
Peripherals
A BluetoothPeripheral
represents a Bluetooth Low Energy profile for interacting with a Bluetooth device. To get a list of all of the BluetoothPeripheral
s that are supported by the Validic Bluetooth Platform:
let peripherals = await ValidicBluetooth.getAllPeripherals();
To get a BluetoothPeripheral definition by its BluetoothPeripheral.ID identifier:
let peripheral = await ValidicBluetooth.getPeripheralInfo(peripheralId);
Permissions
The following permissions are automatically added to project. They must be requested at runtime before the Validic SDK can connect to a Bluetooth Device:
Android >= Android 12
- android.permission.BLUETOOTH_SCAN
- android.permission.BLUETOOTH_CONNECT
Android < Android 12
- android.permission.BLUETOOTH
- android.permission.BLUETOOTH_ADMIN
- android.permission.ACCESS_COARSE_LOCATION
- android.permission.ACCESS_FINE_LOCATION
- android.permission.ACCESS_BACKGROUND_LOCATION
Pair
Some BluetoothPeripheral
profiles require pairing with the device before measurements can be retrieved from the device. These BluetoothPeripheral
s will have RequiresPairing == true
and will have PairingInstruction
that can be used to display to the end user:
try{ val peripheral = await ValidicBluetooth.getPeripheralInfo(2); // A&D BP cuff // do something with peripheral.pairingInstructions console.log(peripheral.pairingInstructions); // then pair val result = await ValidicBluetooth.pair({ "peripheralID": 2 }) } catch (e) { console.log(e) }
Read
To take a reading from a BluetoothPeripheral
device call readPeripheral
try{ val records = await ValidicBluetooth.readPeripheral({ "peripheralId": 2 }) } catch (e) { console.log(e) }
By default Record
s that are collected are automatically submitted to the Validic API. To prevent autosubmitting the readings and submitting them manually to the server, use the autoSubmit
option and use ValidicSession
to submit the records collected.
try{ val records = await ValidicBluetooth.readPeripheral({ "peripheralID": 2, "autoSubmit": false }) await ValidicSession.submitRecords(records) } catch (e) { console.log(e) }
Cancelling an operation
To cancel an inflight Promise
after calling ValidicBluetooth.pairPeripheral
or ValidicBluetooth.readPeripheral
call the ValidicBluetooth.cancelOperation
function. If an operation is currently in place, then the Promise
returned will call its reject function with a cancellation method.
ValidicBluetooth.readPeripheral({ peripheralId:1 autoSubmit:true }) .then(()=>{ console.log("Paired with Peripheral"); }) .catch(e=>{ console.log(e); }); // ... ValidicBluetooth.cancelOperation();
Passive Reading
ValidicBluetooth
allows for registering a set of BluetoothPeripheral
s to scan and read from automatically in the background. Collected Readings are automatically submitted to the Validic API. The peripherals are persisted across reboots. Use an array of BluetoothPeripheral.peripheralId
s to start reading in the background.
await ValidicBluetooth.setPassivePeripherals([1,14,15])
To get a list of BluetoothPeripheral Ids that are being scanning and read in the background
let backgroundPeripherals = await ValidicBluetooth.getPassivePeripherals()
iOS
The host application must be at least launched in the background for readings to be collected from devices when they advertise an available reading.
Android
If the host application is closed by the user and a Bluetooth Peripheral advertises a new reading the App will relaunch and collect the reading.
Updated about 1 month ago