shell (cURL) Android (Java) Kotlin iOS (Swift) Python JavaScript (jQuery) Dart

SDK Integration

IMPORTANT NOTE

SDK support & versioning

At Thryve, we have committed ourselves to provide a more robust, efficient and easy to integrate system, as well as coming to a point where we can provide quicker and longer support on our releases.

From SDK Version 4.2.0 onwards, when released, all modules in each of the SDK's ( Android and iOS ) will be published and updated using a Unified Versioning Scheme based on semantic versioning.

But, What does that mean for our integration?

In the short term, it means easily understanding the version of the SDK you're using, it's features, any new changes, any known issues, and ensuring module inter-compatibility.

When should we upgrade to a new SDK Version?

Ideally, we would love to be able to provide you with our most recent integrations and improvements, but we understand that changes in a running environment take time and therefore we want to be able to help you adapt to those > changes. Stay tuned to know more about the process we're building to ensure you can get the most out of our system.

The SDK allows your users to connect 3rd party health data sources like Apple Health, Fitbit or Withings with your app through Thryve, as well as native data retrieval and data collection through specific SDK modules.

Integrating the Thryve SDK within your Android and iOS apps (→ see sections for iOS or Android respectively) is a plug & play process and will allow you to establish a data source connection with only two requests:

  1. Generate a Thryve token (and store it with your user)
  2. Bring up the data sources connection for this user

If a successful connection is established, your users’ data will start to flow to Thryves data warehouse, where you can retrieve it through our wearable API at any time.

This standard process can be flexibly adapted and expanded to match exactly your needs – from individual styling (→ see custom data source connection screen) to the integration of on-device data retrieval of native data sources (→ see HealthKit, Google Fit Native and SHealth modules) and on-device health data generation (→ see Google Fit Native).

Get access to Thryve's SDK and integrate 500+ wearables with your appGet started

SDKs and Modules

Thryve’s SDKs for Android and iOS app consist of one CoreSDK and several optional modules, you only need to integrate the functionalities you want to use. SDK modules are separated libraries that can coexist in your application environment.

Thryve Core SDK

The CoreSDK brings everything you need to allow your users to connect all OAuth and Direct Access data sources with your app via Thryve. The CoreSDK contains all necessary routines to create Thryve access tokens, to display Thryve’s or your own data source connection page and to allow your users to establish a data source connection.

Thryve Commons module

The Thryve Commons module is required to use any of the additional SDK modules. This module provides database and server synchronization logic needed for the additional modules.

Native data source modules

The SDK modules for Apple Health, Google Fit (native) and Samsung Health allow your users to connect and share data from native data sources with you. The corresponding SDK modules allow to establish a data source connection with native sources and to retrieve data.

BGM module (experimental)

The BGM module allows for data access of selected connected blood glucose monitors from i-Sense, B.Braun and Roche via Bluetooth. The module allows your users to find, connect and sync data of these devices within your app.

iOS integration

Experimental modules: BGMModule

In a quest to provide the most comprehensive access to connected devices, we are continuously exploring new ways of device access. To get new devices into your hands as fast as possible, we release new features on an ongoing basis. Please note, that as of now, the BGMModule is in testing and enhancement phase and only released as a "experimental" version - please let us know in case of any peculiarities!

The iOS SDKs and modules for native apps are designed as iOS frameworks. As previously described, the CoreSDK provides all necessary methods to allow your users to establish a data sources connection with OAuth and Direct Access data sources. The different modules are extensions to the SDK’s functionality with additional data retrieval routines. It is required to instantiate the CoreConnector when using any of the additional modules. The integration of the Apple Health Module is required to access data through Apple HealthKit. The CoreSDK and all modules have separate constructors to set up the corresponding object instance needed to call the desired method.

Integrating the iOS framework

To integrate the Thryve SDK with your iOS app, please download the latest SDK and required modules and follow these steps:

Add framework file

Right-click your Xcode project's root and add a New Group. This is where the Framework will be added. When the group is created, drag and drop the dedicated framework file from Finder into the newly created group. A dialog will open, please select Copy items if needed, Create folder references and select the targets you want to add the Framework onto.

Following the import, the framework will appear in the left navigation hierarchy of the project.

When the framework is added to the project, link it with the target. Select the project root > target > General:

Next, add the framework in the Embedded Binaries and Linked Frameworks and Libraries sections by clicking on the +-sign. Select the thryve_CoreSDK.framework in the appearing dialog.

If you have followed the import correctly, the screen should look like this:

Enable BitCode

Select the project root > target > Build Settings. Search for Enable Bitcode and select Yes.

Import framework

Now you should be able to import the dedicated reference in all classes.

Constructor

To use the library’s functionality, create a CoreConnector-object with the below described constructor. There are two different types of constructors. Depending on the usage of the partnerUserId-String, the getAccessToken()-method will create different results.

import ThryveCore

let connector = CoreConnector(
  appId: "FEh9HQNaa87cwdbB",
  appSecret: "NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM",
  partnerUserId: "FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk",
  language: "en"
)
Code Description
CoreConnnector(appId: String, appSecret: String) Creates the CoreConnector-object when using the following correct parameters.
Parameters:

appId: The application code you received upon signing the cooperation as a String
appSecret: Your application secret you received upon signing the cooperation as a String

CoreConnnector(appId: String, appSecret: String, partnerUserId: String) Creates the CoreConnector-object in the same way as the above constructor, but with a partnerUserId.
Additional Parameter:

partnerUserID: An optional customerID, which allows Thryve to persistently relate a token to a user. If provided, Thryve will return the last valid accessToken previously created for this user instead of generating a new one e.g. FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk

Note: partnerUserID is only allowed to consist of alphanumeric characters and only a dash, "-", as a special character.

CoreConnnector(appId: String, appSecret: String, language: String) Creates the CoreConnector-object in the same way as the above constructor, but with a user related language.
Additional Parameter:

language: Optionally determines the language setting for the corresponding user. Will be set as a string of the country code, e.g.: en. We currently support five languages: English, German, Spanish, French and Italian. If not set, the default language partner will be used.

Generate a Thryve user

All data stored of any given end-user is linked to a pseudonymous Thryve user. This user is generated on backend side when calling the getAccessToken method. The method returns an accessToken, which is required for connecting data sources, uploading data or retrieving data for the user.

Additionally, you can set a unique identifier for the Thryve user. We call this the partnerUserID. Please ensure that the partnerUserID is an unguessable string generated e.g. through a hash-function. We suggest at least 32 digits, that may contain both digits, characters, and a dash „-„, as a special character.

To set this unique identifier, please add the partnerUserID when calling the getAccessToken method. If an accessToken is returned, you defined your user’s partnerUserID successfully.

connector.getAccessToken(completionHandler: { (token, error) in
  //do code
})
Code Description
getAccessToken(completionHandler: @escaping (_ accessToken: String?, _ error: Error?) -> Void) Retrieves a new Thryve accessToken. If a partnerUserId was not previously set, it creates a new user. Otherwise, it will resend a corresponding accessToken for the existing user with the corresponding partnerUserID.

This method runs asynchronously and, when finished, returns the result or error through the completion handler. Please check the code section on the right for an example response.

Name Type Description
completionHandler @escaping (_ accessToken: String?, _ error: Error?) -> Void Callback for when the operation finishes with access token or error.

Display data source connection screen

Having received the accessToken for your user, the following method allows your user to connect their 3rd party devices via the data source connection screen. To give you a head-start we provide a ready-to-use WebView for the data source connection screen that you can display in your app (see below) – providing a seamless experience for your users.

The Thryve data sources selection screen uses the web view of the OS. To implement the pre-built data source connection screen, create the child of CoreWebViewController class and CoreWebViewDelegate class. To display the list of available data sources, please use loadDataSourceConnection. An example implementation is displayed on the right.

class ViewController: CoreWebViewController, CoreWebViewDelegate {

    var connector: CoreConnector?

    var connection: Bool = true

    var instantRevoke: Bool = false

    var source: Tracker?

    override func viewDidLoad() {
        super.viewDidLoad()
        coreWebViewDelegate = self
        loadDataSourceConnection()
    }

    func webView(_ webView: WKWebView, source: Tracker?, connected: Bool, error: Error?) {}

}
Code Description
connector: CoreConnector? A CoreWebViewDelegate property. A CoreConnector instance.
loadDataSourceConnection() Generates and shows the data source URL inside the web view for the user related to the last retrieved accessToken.
• hint: call this method directly inside the viewDidLoad()

iOS extensions

The following chapter describes additional functionalities of the CoreSDK and modules. You can download the SDK framework files and the sample project in the above chapter.

CoreSDK: Custom data source connection

If you want your users to connect their data sources through your own customizable data source connection screen or webpage, you can use the SDK's direct connection and revoke functionality. For security reasons we encourage you using the device browser for opening the URLs and not WKWebView. For the corresponding data source, please refer to the data sources overview.

A simplistic implementation of creating a connection URL using getConnectDataSourceUrl can be accomplished with the following example. Revoking the direct connection can be accomplished in a similar way using getRevokeDataSourceUrl instead.

// ...
connector.getConnectDataSourceUrl(to: Tracker(.fitbit), completionHandler: openUrlByBrowser)
// ...
private func openUrlByBrowser(url: URL?, error: Error?) {
    guard let url = url else {
        Logger.e(error)
        return
    }
    UIApplication.shared.open(url)
}
Code Description
getConnectDataSourceUrl(to tracker: Tracker, completionHandler: @escaping (URL?, Error?) -> Void) Requests an URL for a connection of the given Tracker (data source) and provides a completion handler returning the connection URL or Error
getRevokeDataSourceUrl(from tracker: Tracker, instant: Bool = false, completionHandler: @escaping (URL?, Error?) -> Void) Requests an URL for revoking a connection of the given Tracker (data source) and provides a completion handler with the revoke URL or Error

CoreSDK: PartnerDataUpload

The PartnerDataUpload methods allows to upload custom data from the app to the Thryve data warehouse which is not data recorded by any data source. This might be a users demographic data like birthdate and gender or certain indications needed for health status calculation or other analytics of Thryve’s interpretation layer.

Data can be uploaded as DailyDynamicValue, or, for slowly or never changing values as ConstantValues. You can access the data uploaded through the SDK like any other data via our API.

Please refer to the sections Accessing the API and the Interpretation Layer for more information.

Health status/Interpretation layer data types

The following values are required for health status and interpretation layer analytics and need to be uploaded via the PartnerDataUpload:

DailyDynamicValue

let day = Date()
let payload = CustomerValue.CustomerPayload(value: "10", of: DataType(1000, .long), on: day)
let data = CustomerValue(data: [payload])

connector.uploadDailyDynamicValue(data: data) {
  (success, e) in
  debugPrint(e)
}
Code Description
uploadDailyDynamicValue(data: CustomerValue, completionHandler: @escaping (Bool, Error?) -> ()) Uploads DailyDynamicValue for given day of date and type. Value is passed as String. The completion handler reports about the status of the successfully implemented interface or will return an error otherwise.
Name Type Description
completionHandler @escaping (Bool, Error?) -> () Callback returns response status and error

ConstantValue

let payload = CustomerValue.CustomerPayload(value: "5", of: DataType(9050, .long))
let data = CustomerValue(data: [payload])

connector.uploadConstantValue(data: data) {
  (succes, e) in debugPrint(e)
}
Code Description
uploadConstantValue(data: CustomerValue, completionHandler: @escaping (Bool, Error?) -> ()) Uploads ConstantValue for given type. Value is passed as String. The completion handler reports about the status of the successfully implemented interface or will return an error otherwise.
Name Type Description
completionHandler @escaping (Bool, Error?) -> () Callback returns response status and error otherwise

UserInformation

let user = User(height: 173, weight: 174.2, birthdate: "1990-01-18", gender: Gender.male)
connector.uploadUserInformation((data: user) {
  (succes, e) in debugPrint(e)
}
Code Description
uploadUserInformation(data: User, completionHandler: @escaping (Bool, Error?) -> ()) Uploads UserInformation for the given User object. The completion handler reports about the status of the successfully implemented interface or will return an error otherwise.
Name Type Description
completionHandler @escaping (Bool, Error?) -> () Callback returns response status and error

CoreSDK: Get UserInformation

You can retrieve user information directly with the CoreSDK, without the need to call the Wearable API. The implementation makes use of an UserInformation-object that will be wrapped inside a list. Please refer to the right code section for an example.

self.viewModel.connector.getUserInformation(onSuccess: { (userInfoArray, error) in
  // Data inside 'userInfoArray'
})
Code Description
getUserInformation(completionHandler: @escaping ([UserInformation], Error?) -> ()) Retrieves an array of UserInformation in onSuccess.
Name Type Description
completionHandler @escaping ([UserInformation], Error?) -> () A callback containing array of UserInformation or error. UserInformation( authenticationToken: String, partnerUserID: String?, height: Int?, weight: Double?, birthdate: String?, gender: String?, connectedSources: [ConnectedSource])

authenticationToken: Thryve access token (String)
partnerUserID: PartnerUserID (String)
height: Height in cm (Integer)
weight: Weight in kg (Double)
birthdate: Birth date String in YYYY-MM-dd format
gender: Gender from Gender, i.e. male, female, genderless
connectedSources: Array of ConnectedSource. ConnectedSource(dataSource: Int, connectedAt: String), whereas connectedAt is a String timestamp of the connection time and dataSource is the Thryve ID for the connected source.

AppleHealth: Integration

To integrate Apple’s HealthKit with your iOS app, you need to integrate the AppleHealth module of Thryve’s SDK. This will allow your users to connect with Apple Health and to automatically trigger a background routine to retrieve the latest health data.

Set your app's permission

<key>NSHealthShareUsageDescription</key>
<string>This app needs permission to share your health data</string>
<key>NSHealthUpdateUsageDescription</key>
<string>This app needs permission to update your health data</string>

To retrieve health data via Apple HealthKit with the Thryve SDK you need to following pemissions to your app's info.plist-file:

For further details checkout the code example on the right. In addition, you also need to add HealthKit in the entitlements list (Target → Signing & Capabilities → add (+) → HealthKit) of your app with "Background Delivery" enabled.

Start with the constructor

Before calling any method of the Apple Health module, please create the corresponding constructor.

import ModuleAppleHealth

let hKconnector = HKConnector()
Code Description
HKConnector() Creates the HKConnector-object

Check if Apple Health is available on the device

We recommend to use the isAvailable method at the beginning of every session before using any other methods to avoid errors. If Apple Health is not available all other methods will fail and result in errors.

Code Description
isAvailable: Bool {return HKHealthStore.isHealthDataAvailable()} Checks if Health Kit is supported and available on the device

Check if Apple Health is already connected

The isEnabled method will check if the authorizeHealthKit returned a success boolean in the past. If the method returns false, you need to ask your user to authorize data access for your app with the authorizeHealthKit method. We recommend to use this method before using any method for data retrieval to avoid errors.

Code Description
isEnabled(for service: Service) -> Bool Use with .healthKit. Checks, if HealthKit-integration is enabled.

Get user authorization

Before you can retrieve any data, your app needs to be authorized to access Apple Health data by your users. To get authorization, use the authorizeHealthKit method and the corresponding dialogue will be shown on top of your app.

When using authorizeHealthKit specify the data you want to access by listing the corresponding HKObjectType.

Code Description
authorizeHealthKit(types: Set HKObjectType, completionHandler: @escaping (Set HKObjectType , Bool, Error?) -> ()) -> ()) This method launches the Apple Health permission screen with the given requested types.

AppleHealth: Data retrieval

To initiate the data retrieval, call the method start. If this method was called the module is able to fetch data through HealthKit until stop was called or the user revoked the authorization in the AppleHealth app.

Code Description
start(types: Set HKObjectType, completionHandler: @escaping (Bool, Error?) -> ()) Starts HealthKit integration, which compromises the creation of a secure keychain storage for any necessary temporary data, sets up a connection to the Apple HealthKit interfaces, and performs a call for background delivery of data for the current app's session. To receive data beyond the current app session, check enableBackgroundDeliveryFor. Call this function in the "completionHandler" of authorizeHealthKit
stop
(completionHandler: @escaping (Bool, Error?) -> ())
Stops HealthKit integration, can be called anytime. The method will notify the backend where the connection will be revoked. isEnabled will return false.

Background data retrieval

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Use any types you require or HKConnectorType.allTypes
        let types = [
            HKConnectorType.heartRate,
            HKConnectorType.stepCount
        ]
        //When apple's Health app decides to, it will wake your application through didFinishLaunchingWithOptions.
        //Once awoken, HealthKit waits a few seconds to see if said app wants to renew it's observing query contracts.
        //calling this method as early as possible renews those query contracts.
        HKConnector().enableBackgroundDeliveryFor(types: types)
        // Override point for customization after application launch.
        return true
    }

To enable background fetch (retrieving data when your app is closed or idle), call the enableBackgroundDeliveryFor method with the corresponding data types inside the didFinishLaunchingWithOptions method of AppDelegate. Apple requires the contained logic to be run in the first seconds of the app startup for data to be delivered, hence the AppDelegate position. It is not needed to wrap the method in an authorize call. Please refer to the sample code for more information.

For iOS 15 and watchOS 8 and onwards, you must enable the HealthKit Background Delivery by adding the com.apple.developer.healthkit.background-delivery entitlement to your app. If your app doesn’t have this entitlement, the enableBackgroundDelivery(for:frequency:withCompletion:) method fails with an HKError.Code.errorAuthorizationDenied error. Please refer to the official documentation for more information.

Code Description
enableBackgroundDelivery
For(types: Set HKObjectType)
Registers the SDK to receive background updates from HealthKit. This is called automatically after Start(), and must always be called in didFinishLaunchingWithOptions inside AppDelegate. The frequency of the updates varies per user device's configuration, caller app usage patterns, and a set of minimum gaps. The frequency for data retrieval can range from 1h to 12h. You can find more information here.

Manual data retrieval

To manually trigger the data retrieval, e.g., when a user clicks a button or every time the application is opened, use the synchronizeEpoch and synchronizeDaily method to retrieve the corresponding data types.

Code Description
synchronizeEpoch( types: Set\, completionHandler: @escaping (Bool, Error?) -> Void) Performs Epoch synchronization from last upload date to today. Call this function in order to synchronize the epoch data immediately. The parameter completionHandler_ reports the status of synchronization for this method.
synchronizeEpoch( startDate: Date, endDate: Date, types: Set\, completionHandler: @escaping (Bool, Error?) -> Void) Performs Epoch synchronization between given dates, with a maximum of 30 days. If the difference between startDate and endDate is more than 30 days, the SDK will count from the end date 30 days back. The parameter completionHandler reports the status of synchronization for this method.
synchronizeDaily( types: Set\, completionHandler: @escaping (Bool, Error?) -> Void) Performs Daily synchronization from last upload date to today. Call this function in order to synchronize the epoch data immediately. The parameter completionHandler reports the status of synchronization for this method.
synchronizeDaily( startDate: Date, endDate: Date, types: Set\, completionHandler: @escaping (Bool, Error?) -> Void) Performs Daily synchronization between given dates, with a maximum of 365 days. If the difference between startDate and endDate is more than 365 days, the SDK will count from the end date 365 days back. The parameter completionHandler reports the status of synchronization for this method.

Error codes of synchronize methods

Name Type Description
types Set <HKObjectType> Set specified data types to be handled in HealthKit.
completionHandler @escaping (Set <HKObjectType> , Bool, Error?) -> () Completion handler will be called after presenting the Apple Health permission window in order to allow reading access for the selected types. The callback will return the status, if the permission window was successfully presented, and an optional error if the window was not presented properly to the requested HKObjectType set.
completionHandler @escaping (Bool, Error?) -> () Completion handler notifies about the status for starting/stopping integration for every observing query.
service Service Service to check if enabled.
startDate Date The date which will be used as the starting point of a synchronization call. The time should never be later than the endDate or else the data retrieval will fail.
endDate Date The date which will be used as the end point of a synchronization call. The time should never exceed the current time of the device (the exact time this method is called) or else the data retrieval will fail. Please make sure to consider the timezone of the device when setting the time.

AppleHealth: Error codes of synchronize methods

Code Name Description
Code Name Description
70010 HK_SYNC_START_AFTER_NOW the start date set in synchronizeEpoch or synchronizeDaily is set as a date that is in the future
70011 HK_SYNC_END_AFTER_NOW the end date set in synchronizeEpoch or synchronizeDaily is set as a date that is in the future
70012 HK_SYNC_END_BEFORE_START the end date set in synchronizeEpoch or synchronizeDaily is set before the start date

AppleHealth: Method parameters

Name Type Description
types Set <HKObjectType> Set specified data types to be handled in HealthKit.
completionHandler @escaping (Set <HKObjectType> , Bool, Error?) -> () Completion handler will be called after presenting the Apple Health permission window in order to allow reading access for the selected types. The callback will return the status, if the permission window was successfully presented, and an optional error if the window was not presented properly to the requested HKObjectType set.
completionHandler @escaping (Bool, Error?) -> () Completion handler notifies about the status for starting/stopping integration for every observing query.
service Service Service to check if enabled.
startDate Date The date which will be used as the starting point of a synchronization call. The time should never be later than the endDate or else the data retrieval will fail.
endDate Date The date which will be used as the end point of a synchronization call. The time should never exceed the current time of the device (the exact time this method is called) or else the data retrieval will fail. Please make sure to consider the timezone of the device when setting the time.

BGMModule (experimental): Constructor

The BGM module allows to connect connected blood glucose meters from i-Sens, B.Braun and Roche with your app via bluetooth.

The module uses the swift classes CBCharacteristic and CBPeripheral that are wrapped inside the BLEDelegate-protocol that your ViewModel must extent. To use the module, you must handover the ViewModel itself to the BGMModule constructor as well.

class BGMViewModel: ObservableObject {
  private var connector: BGMConnector?
  var source: BGMDevice

  init(_ source: BGMDevice) {
      self.source = source
  }

  func setConnector() {
      if connector == nil {
          connector = BGMConnector(delegate: self, source: source)
      }
  }

  func startScanning() {
      connector?.startScanning()
  }

  func stopScanning() {
      connector?.stopScanning()
  }

  func connect(device: CBPeripheral) {
      connector?.connect(peripheral: device)
  }

  func sync() {
      if racp != nil {
          connector?.sync(racp: racp!)
      }
  }

  func disconnect() {
      connector?.disconnect()
  }

  func delete(source: BGMDevice) {
      connector?.delete(source: source)
  }
}
Code Description
BGMConnector(delegate: ModuleBGM.BLEDelegate, source: ModuleBGM.BGMDevice) Creates the BGMConnector-object. Should be called from within a ViewModel. Parameters:

delegate: The responsible View object to implement BLEProtocol connection callbacks
device: The BGM device mark which will transport the blood glucose data (iSens, bBraun, or rocheAccuChek).

Your ViewModel must implement the protocol BLEDelegate. Please refer to the sample Swift code on the right side.

BGMModule (experimental): Scanning

To initially find your BGM device via Bluetooth, you need to start a scanning process that searches for nearby Bluetooth devices. You can perform this with the BGMConnector via the following two methods:

Code Description
startScanning() Starts the Bluetooth scanning process. This process runs indefinitely.
stopScanning() Stops the Bluetooth scanning process. Does nothing, if it is not running.

The scanning process will not stop, until it is stopped manually. Please ensure to implement proper Threads, if you want to setup a timeout for device search.

BGMModule (experimental): Connection

When the scan finds one or more suitable devices, the BLEDelegate-protocol method ble(didFound peripheral: CBPeripheral, rssi: Int) will be called, handing over the CBPeripheral object. This device can either be stored temporarily for later connection or a connection to pair the device can directly be established.

Code Description
connect(peripheral: CBPeripheral) Connects to the given BluetoothDevice. Stores pairing information in the background. If a connection is active and paired the ble(ready racpCharacteristic: CBCharacteristic)-method from BLEDelegate protocol will be called and data can be synchronized.
disconnect() Disconnects the Bluetooth device. The pairing information stays valid.
delete(source: ModuleBGM.BGMDevice) Deletes the Bluetooth device by removing the pairing information as well.

BGMModule (experimental): Syncing

The synchronization process should be executed after the device has been successfully connected and the CBCharacteristic has been handed over via the BLEDelegate protocol ble(ready racpCharacteristic: CBCharacteristic) method. The sync-method will perform the synchronization of recent BloodGlucose data in the background (up to one week, if the data has not been synchronized before) and will perform a direct upload to the Thryve data warehouse. When the upload succeeds, the disconnect of the BGMConnector will be executed automatically. The method is structured as followed:

Code Description
sync(racp: CBCharacteristic) Performs a background synchronization of the BloodGlucose data. A debug printout will be performed, if the synchronization was successful.

Android integration

IMPORTANT NOTE

Android SDK 4.9.3 and later was built using Kotlin 1.6.0. For more information see kotlinlang.org/docs/compatibility-modes. Also, please ensure that the compileSdkVersion must be at least 31.

Experimental module: BGMModule

Please note the all "experimental modules", i.e. BGMModule, are implementations that are currently not maintained by Thryve anymore and have not been tested with various test devices or a big user base. Please keep this in mind when considering to use those modules in a production environment.

The Android SDKs and modules are standard .aar-libraries. As previously described, the CoreSDK provides all necessary methods to allow your users to establish a data sources connection with OAuth and Direct Access data sources. The different SDK modules are extensions to the SDK’s functionality with additional data retrieval routines. It is required to instantiate the CoreConnector when using any of the additional modules. The CoreSDK and all modules have separate constructors to set up the corresponding object instance needed to call the desired method.

Integrating the .arr libraries

module build.gradle

...
  ...
  android {
    ...
    compileOptions {
      sourceCompatibility 1.8
      targetCompatibility 1.8
    }
    kotlinOptions {
        jvmTarget = 1.8
    }
    // Only needed, if CommonsModule is added
    packagingOptions {
        pickFirst 'lib/x86_64/libsqlcipher.so'
        pickFirst 'lib/armeabi-v7a/libsqlcipher.so'
        pickFirst 'lib/x86/libsqlcipher.so'
        pickFirst 'lib/armeabi/libsqlcipher.so'
        pickFirst 'lib/arm64-v8a/libsqlcipher.so'
    }
  }
  ...
  dependencies {
    ...
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.gms:play-services-location:20.0.0'

    // Referenced in project's build.gradle
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version'

    implementation files('libs/thryve_core_sdk_4.11.2.aar')

    // CommonsModule import needed for other modules
    implementation files('libs/thryve_module_commons_4.11.2.aar')
    // Optional modules
    implementation files('libs/thryve_module_shealth_4.11.2.aar')
    implementation files('libs/thryve_module_gfit_4.11.2.aar')
    ...
    // dependencies for network and others
    implementation "com.google.code.gson:gson:$gson"
    implementation "androidx.legacy:legacy-support-v4:$legacySupport"

    implementation "io.reactivex.rxjava2:rxjava:$rxJava2"
    implementation "io.reactivex.rxjava2:rxandroid:$rxAndroid2"
    implementation "io.reactivex.rxjava2:rxkotlin:$rxKotlin"
    implementation "io.github.reactivecircus.cache4k:cache4k:$cache4k"

    // dependencies for background sync (Google Fit, Samsung Health)
    implementation "androidx.work:work-runtime:$work"
    implementation "androidx.work:work-runtime-ktx:$work"
    implementation "androidx.work:work-gcm:$work"

    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle"

    implementation "androidx.concurrent:concurrent-futures:$concurrentFutures"
    implementation "androidx.concurrent:concurrent-futures-ktx:$concurrentFutures"

    // dependencies for Google Fit
    implementation "com.google.android.gms:play-services-auth:${playServicesAuth}"
    implementation "com.google.android.gms:play-services-fitness:${playServicesFitness}"

    // dependencies for internal database systems
    implementation "androidx.room:room-runtime:$room"
    implementation "androidx.room:room-ktx:$room"
    implementation "androidx.annotation:annotation:$annotation"

    // dependencies for encryption/auth mechanisms
    implementation "net.zetetic:android-database-sqlcipher:$sqlCipher"
    implementation "androidx.security:security-crypto:$crypto"
  }
buildscript {
    ext.androidXCore = "1.8.0"
    ext.androidxTest = "1.4.0"
    ext.androidXJunit = "1.1.3"
    ext.appCompat = "1.5.0"
    ext.annotation ="1.4.0"
    ext.cache4k = "0.8.0"
    ext.constraintLayout = "2.1.4"
    ext.crypto = "1.1.0-alpha06"
    ext.concurrentFutures = "1.1.0"
    ext.dokka = "1.7.10"
    ext.espressoCore = "3.4.0"
    ext.junit = "4.13.2"
    ext.kotlinPlugin = "1.7.10"
    ext.legacySupport = "1.0.0"
    ext.lifecycle = "2.5.1"
    ext.playServicesLocation = "20.0.0"
    ext.playServicesWearable = "17.1.0"
    ext.playServicesFitness = "21.1.0"
    ext.playServicesAuth = "20.3.0"
    ext.roboelectric = "4.7.3"
    ext.room = "2.4.3"
    ext.rxAndroid2 = "2.1.1"
    ext.rxJava2 = "2.2.10"
    ext.rxKotlin = "2.4.0"
    ext.sentrySdk = "5.5.2"
    ext.sqlCipher = "4.5.0"
    ext.work = "2.7.1"
    ext.gson = "2.8.9"
    ...
}

Add library file

The versions as of May 2022 which can be put to the project or app build.gradle file:

  1. Add the dedicated aar-file to a folder of your project (e.g. libs)
  2. Add implementation files('libs/.aar') to your build.gradle file
  3. Add Kotlin support with annotation processing
  4. Add support for Android AppCompat-Library
  5. Add target and source compatibility for Java 1.8
  6. Add Jvm target for kotlin to version 1.8
  7. For further information please refer to the example build.gradle-script on the right. If CommonsModule is added, add packagingOptions accordingly

Create the constructor

To use the library’s functionality, create a CoreConnector-object with the below described constructor. There are two different types of constructors. Depending on the usage of the partnerUserId-String, the getAccessToken()-method will create different results.

// Application, Activity or Service Android Context
val context: Context = this

val appId: String = "FEh9HQNaa87cwdbB"
val appSecret: String = "NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"

// Connector object without partnerUserId
val connector = CoreConnector(context, appId, appSecret)

val partnerUserId: String = "FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk"

// Connector object with partnerUserId
val connector = CoreConnector(context, appId, appSecret, partnerUserId)

val language: String = "en"

// Connector object with partnerUserId
val connector = CoreConnector(context, appId, appSecret, partnerUserId, language)
Code Description
new CoreConnector(Context context, String appId, String appSecret) Creates the CoreConnector-object when using the following correct
parameters:

context: Default Android Context
appId: The application code you received upon signing the cooperation as a String
appSecret: Your application secret you received upon signing the cooperation as a String

new CoreConnector(Context context, String appId, String appSecret, @Nullable String partnerUserId) Creates the CoreConnector-object in the same way as the above constructor, but with a partnerUserId.
Additional Parameter:

partnerUserId: A customer ID, which allows Thryve to persistently relate a token to a user. If provided, Thryve will return the last valid accessToken previously created for this user instead of generating a new one e.g. FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk

Note: PartnerUserID is only allowed as alpha numeric characters.

new CoreConnector(Context context, String appId, String appSecret, @Nullable String partnerUserId, @Nullable String language) Creates the CoreConnector-object in the same way as the above constructor, but with a user related language.
Additional Parameter:

language: Optionally determines the language setting for the corresponding user. Will be set as a string of the country code, e.g.: en. We currently support five languages: English, German, Spanish, French and Italian. If not set, the default partner language will be used.

Generate a Thryve user

All data stored of any given end-user is linked to a pseudonymous Thryve user. This user is generated on backend side when calling the getAccessToken method. The method returns a ThryveResponse holding the access token as data, which is required for connecting data sources, uploading data or retrieving data for the user.

Additionally, you can set a unique identifier for the Thryve user. We call this the partnerUserID. Please ensure that the partnerUserID is an unguessable string generated e.g. through a hash-function. We suggest at least 32 digits, that may contain both digits, characters, and a dash „-„, as a special character.

To set this unique identifier, please add the partnerUserID when creating the CoreConnector. If an access token is returned, you defined your user’s partnerUserID successfully.

// Must be called in background thread to avoid NetworkOnMainThreadException
val thryveResponse = connector.getAccessToken()

if (thryveResponse.successful) {
    token = thryveResponse.data
} else {
    // process thryve thryveResponse.error
}
Code Description
fun getAccessToken(): ThryveResponse<String> Retrieves a new Thryve access token as part of ThryveResponse.data. If a partnerUserId was not previously set, it creates a new user and access token on each call. Otherwise, it will return an existing access token for the existing user with the corresponding partnerUserID.

Display data source connection screen

If you have received the access token for your user, the following method allows your user to connect their 3rd party devices via the data source connection screen. To give you a head-start we provide a ready-to-use WebView for the data source connection screen that you can display in your app (see below) – providing a seamless experience for your users.

The Thryve data sources selection screen uses the web view of the OS. To implement the pre-built data source connection screen, an Android-WebView-instance must be passed as a parameter to the method:

final webView = findViewById(R.id.web_view);

connector.handleDataSourceConnection(webView);
Code Description
void handleDataSourceConnection (WebView webview) Generates and shows the data source URL inside the web view for the user related to the last retrieved accessToken (valid for 1h).
webView: Plain android.webkit.WebView-object. Must not be null. Warning: most settings will be overwritten

Android extensions

The following chapter describes additional functionalities of the CoreSDK and modules. You can download the SDK framework files and the sample project in the above chapter.

CoreSDK: Custom data source connection

If you want your users to connect their data sources through your own customizable data source connection screen or webpage, you can use the SDK's direct connection and revoke functionality.

Use the data source ID to display the authorization page of the corresponding data source, e.g. use ID 1 when connecting Fitbit. For the corresponding data source IDs, please refer to the data sources overview.

A simplistic implementation of creating a direct connection using directConnection can be accomplished with the following example. Revoking the direct connection can be accomplished in a similar way using directRevoke instead.

Observable
    .fromCallable {
        // get the direct connection URL
        connector.getConnectDataSourceUrl(selectedDataSource)
    }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ response ->
        if (response.succesfull) {
            // start an intent typically opening the device browser
            val browserIntent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse("$url&redirect_uri=<your redirect uri getting back to your app>")
                )
            startActivity(browserIntent)        
        } else {
            // process thryveResponse.error
        }

    }, {
        // handle any thrown error here
    })
    .dispose()
Code Description
fun getConnectDataSourceUrl(dataSourceType: Int): ThryveResponse<String> Requests an URL for a connection of the given data source type which can be used in a custom app internal WebView or the device browser.

dataSourceType: integer based data source type (e.g. 1 for Fitbit)

Returns ThryveResponse containing the url as data in case of success, or an error otherwise.
fun getRevokeDataSourceUrl(dataSourceType: Int, instant: Boolean = false): ThryveResponse<String> Requests an URL for revoking a connection of the given data source type which can be used in a custom app internal WebView or the device browser.

dataSourceType: integer based data source type (e.g. 1 for Fitbit)
instant: Set to true indicating to directly revoke the direct connection without further user interaction. Default is false

Returns a ThryveResponse containing the url as data in case of success, or an error otherwise.

For usage examples, please refer to the ThryveSample Android Studio project.

CoreSDK: PartnerDataUpload

The PartnerDataUpload methods allows to upload custom data from the app to the Thryve data warehouse which is not data recorded by any data source. This might be a users demographic data like birthdate and gender or certain indications needed for health status calculation or other analytics of Thryve’s interpretation layer.

Data can be uploaded as DailyDynamicValue, or, for slowly or never changing values parameters as ConstantValues.

Please refer to the sections Accessing the API and the Interpretation Layer for more information.

Health status/Interpretation layer data types

The following values are required for health status and interpretation layer analytics and need to be uploaded via the PartnerDataUpload:

DailyDynamicValue

val date: Date = new Date();
val dailyDynamicValueType: Int = 5020;
val value: Long = 70.5;

// Must be called in background thread to avoid NetworkOnMainThreadException
val thryveResponse = connector.uploadDailyDynamicValue(date, dailyDynamicValueType, value);
// process thryveResponse
Code Description
fun uploadDailyDynamicValue(date: Date, type: Int type, value: Any): ThryveResponse<Boolean> Uploads a daily dynamic value for a given day (date) and type. For types please check the Biomarkers documentation. Returns a ThryveResponse containing true as data in case of success, or false otherwise.

ConstantValue

val constantValueType: Int = 9050;
val value: Long = 2;

// Must be called in background thread to avoid NetworkOnMainThreadException
val thryveResponse = connector.uploadConstantValue(constantValueType, value);
// process thryveResponse
Code Description
fun uploadConstantValue(type: Int, value: Any): ThryveResponse<Boolean> Uploads a constant value for given type. Date is not needed. For types please check the Biomarkers documentation. Returns a ThryveResponse containing true as data in case of success, or false otherwise.

CoreSDK: Upload UserInformation

You can upload user information like height, weight, gender and others with the CoreSDK. The function returns a ThryveResponse containing true as data in case of success, or false otherwise. Please refer to the sample code section for further details.

// Must be called in background thread to avoid NetworkOnMainThreadException
val user = new User(173, 74.2, "1990-01-18", Gender.MALE);
val thryveResponse = connector.uploadUserInformation(user);
// process thryveResponse
Code Description
fun uploadUserInformation(user: User): ThryveResponse<Boolean> Uploads user information for the given user object:
public User(int height, double weight, String birthdate, Gender gender)

height: Height in cm (Integer)
weight: Weight in kg (Double)
birthdate: Birth date String in YYYY-MM-dd format
gender: Gender from enum, i.e. MALE, FEMALE, GENDERLESS and returns ThryveResponse containing true as data in case of sucess, or false otherwise.

CoreSDK: Get UserInformation

You can retrieve user information directly with the CoreSDK, without the need to call the Wearable API. The function returns a ThryveResponse containing a list of UserInformation as data. Please refer to the sample code section for further details.

// Must be called in background thread to avoid NetworkOnMainThreadException
val thryveResponse = connector.userInformation;
if (thryveResponse.successful) {
    userInformation = thryveResponse.data
} else {
    // process thryve thryveResponse.error
}
Code Description
userInformation: ThryveResponse<List<UserInformation>> Retrieves a list of UserInformation objects:
public UserInformation(String authenticationToken, String partnerUserID, int height, double weight, String birthdate, Gender gender, List connectedSources)

authenticationToken: Thryve access token (String)
partnerUserID: PartnerUserID (String)
height: Height in cm (Integer)
weight: Weight in kg (Double)
birthdate: Birth date String in YYYY-MM-dd format
gender: Gender from Enum, i.e. MALE, FEMALE, GENDERLESS
connectedSources: List of connected sources as defined in ConnectedSource(String connectedAt, int dataSource), whereas connectedAt is a String timestamp of the connection time and dataSource is the Thryve ID for the connected source.

CoreSDK: ThryveLogProcessor

When implementing the SDK, this interface will allow you to view the logs that the SDK outputs to the console and respond to them.

...//Application onCreate
 Logger.init(Logger.Verbosity.INFO, listOf(ThryveSentryProcessor(this), CustomProcessor(), ...)
...class ThryveSentryProcessor(val context: Context) : ThryveLogProcessor {

    ...

    override val identifier: String
        get() = ThryveSentryProcessor::class.java.simpleName

    ...

    override fun process(level: Int, tag: String?, msg: String?, throwable: Throwable?) {
        if (throwable != null && level == Log.ERROR) {
            Sentry.captureException(throwable, "$msg")
        } else {
            if (level != Log.WARN && level != Log.ERROR) {
                Sentry.addBreadcrumb("$tag::" + (msg ?: throwable?.localizedMessage ?: throwable?.message ?: return))
            } else {
                Sentry.captureMessage(
                    "$tag " + (msg ?: throwable?.localizedMessage ?: throwable?.message ?: return),
                    when (level) {
                        Log.WARN -> SentryLevel.WARNING
                        Log.ERROR -> SentryLevel.ERROR
                        else -> return
                    }
                )
            }
        }
    }

Implementing the interface requires overriding the next methods/values:

Code Description
val identifier : String During logging, this identification is used to verify the registered processors.
fun process(@Logger.Level level: Int, tag: String?, msg: String?, throwable: Throwable? = null) When an event is received, the SDK's internal logging tools invoke this method. The processor should then parse it and treat it properly.

SHealth: Integration

private fun toggleSHealthIntegration() {
    if (!sConnector?.isActive()) {
        sHealthPermissions = SHealthDataType.values().asList()
        sConnector?.authorize(this, sHealthPermissions, { granted ->
            if (granted) {
                sConnector?.start(sHealthPermissions) {
                    showMessage("SHealthModule start result: ${it.data}")
                }
            } else {
                showMessage("SHealthModule not authorized")  
            }
        }, { e ->
            showMessage("Error: ${e.message}")
            sConnector?.stop {
                showMessage("SHealthModule stop result: ${it.data}")
            }
        })
    } else {
        sConnector?.stop {
            showMessage("SHealthModule stop result: ${it.data}")
        }
    }
}

To integrate Samsung Health with your Android app, you need to add the SHealth module of Thryve’s SDK. This will allow your users to connect with Samsung Health and automatically trigger a background routine to retrieve the latest health data.

Initiate the Android WorkManager

class App : Application, Configuration.Provider {
    override fun getWorkManagerConfiguration() =
            Configuration.Builder()
                    .setMinimumLoggingLevel(Log.VERBOSE)
                    .build()

The scheduling behaviour of the synchronization service of the Samsung Health SDK module requires the custom configuration and initialization of the Android WorkManager Make sure to use the WorkManagerInitializer in your Application class by implementing Configuration.Provider. Please refer to the Kotlin/Java code sample on the right side of the documentation for guidance.

Create the constructor object

Before calling any method of the SHealth module, please create the corresponding constructor object.

import com.thryve.connector.shealth.SHealthConnector

sHealthConnector = SHealthConnector(context, requestedTypes);
Code Description
SHealthConnector(private val context: Context, connectedTypes: List) Creates the SHealthConnector object.

Check if Samsung Health is available on the device

We recommend to use the isAvailable method at the beginning of every session before using any other methods to avoid errors. If Samsung Health is not available all other methods will fail and result in errors.

Code Description
isAvailable: Boolean Checks if the device supports Samsung Health (if Samsung Health app is installed and is available to the Thryve SDK).

Check if Samsung Health is already connected

The isActive() method will check if the start method was called successfully and if the connection is still active. If the method returns false, you trigger the connection by using the start method. We recommend to use this method before using any method for data retrieval to avoid errors.

Code Description
fun isActive(): Boolean Checks if SHealth integration is active. Can be used for app internal logic or user feedback for GUIs etc.

Get user authorization

Before you can retrieve any data, your app needs to be authorized to access Samsung Health data by your users. To get authorization, use the authorize method and the corresponding dialogue will be shown on top of your app.

When using authorize specify the data you want to access by listing the corresponding SHealthDataType. Only if the user grants permission to access the data, any data retrieval can be performed.

Code Description
fun authorize(sHealthPermissions, callback) This method launches the Samsung Health permission screen with the given requested types. Call this function before start

Check for authorization status

Samsung Health allows developers to understand if the user has granted access to Samsung Health data and for what data types. We recommend to use this method before retrieving health data to check if the permissions are still active and to ensure permissions for the requested data types are granted.

Code Description
fun arePermissionsAcquired(): Boolean? Checks whether a user has granted permission to access one or more data types.
fun getAcquiredPermissions(): List? Returns a list (with 0 to N values) of data types the user has currently granted access to via the Shealth Permission Manager. Checks which permissions from the current permission set are considered acquired by the Shealth Permission Manager. If the permission check request failes, null will be returned.

If the method arePermissionsAcquired returns false or getAcquiredPermissions does not return a data type you want access to, please instruct your user to manually grant access in the Samsung Health app. This is needed as the permission screen dialogue can only be requested once for each data type.


Example of informing user about missing
authorization of SHealthPermission

SHealth: Data retrieval

To initiate the data retrieval, call the method start after acquiring user permission with authorize. The module will fetch data from Samsung Health until stop is called or the user revoked the authorization in the Samsung Health app.

Code Description
fun start(types: List, callback: ((ThryveResponse<Boolean>) -> Unit)?) Starts the Samsung Health service data retrieval and upload service with a list of SHealthDataTypes. It is accompanied with a callback for further details.
fun stop(callback: ((ThryveResponse<Boolean>) -> Unit)?) Stops the Samsung Health service. Does nothing if service is not running. It is accompanied with a callback for further details.

Background data retrieval

The background retrieval of data from Samsung Health will be started automatically when calling start successfully. No further action is required.

Manual data retrieval

To manually trigger the data retrieval, e.g., when a user clicks a button or every time the application is opened, use the synchroniseEpoch and synchroniseDaily method to retrieve the corresponding data types.

Code Description
fun synchroniseEpoch(types: List) Performs Epoch synchronization from last upload date to today with a list of SHealthDataTypes. Call this function in order to synchronize the epoch data immediately.
fun synchroniseEpoch(startDate: Date, endDate: Date, types: List) Performs Epoch synchronization between given dates, with a maximum of 30 days, with a list of SHealthDataTypes. If difference is longer than 30 days, end date - 30 days is used as start date. Call this function in order to synchronize epoch data immediately.
fun synchroniseDaily(types: List) Performs Daily synchronization from last upload date to today with a list of SHealthDataTypes. Call this function in order to synchronize epoch data immediately.
fun synchroniseDaily(startDate: Date, endDate: Date, types: List) Performs Daily synchronization between given dates, with a maximum of 365 days, with a list of SHealthDataTypes. If difference is longer than 365 days, end date - 365 days is used as start date. Call this function in order to synchronize the epoch data immediately.

Synchronize Methods Error Codes

Code Name Description
60001 ACCESS_TOKEN_INVALID No valid access token found. See Generate a Thryve user token.
60010 SYNC_START_AFTER_NOW The start date set in synchroniseEpoch or synchroniseDaily is set as a date that is in the future.
60011 SYNC_END_AFTER_NOW The end date set in synchroniseEpoch or synchroniseDaily is set as a date that is in the future.
60012 SYNC_END_BEFORE_START The end date set in synchroniseEpoch or synchroniseDaily is set before the start date.

SHealth: Method parameters

Name Type Description
Success callback () -> () Callback if authorize was successful.
Error callback (Exception) -> () Callback if authorize had an exception. If the Samsung Health is not available SHealthIntegrationException will be thrown. In case the types are invalid IllegalArgumentException will be thrown.
ThryveResponse callback (ThryveResponse) -> () Callback containing ThryveResponse to check data or potential error.

Google Fit Native: Integration

Disclaimer: unreliable/discrepant Google Fit data:
Please acknowledge that data drawn from Google Fit REST and/or Google FitNative can deviate considerably from the data shown in the Google Fit app (e.g. up to 1000 steps difference). According to Google, it's due to the calculation engine that creates temporary differences. This has been a known issue and many clients are experiencing these persistent differences. Please refer to Google Fit official reference for further details.

To integrate Google Fit native with your Android app, you need to integrate the GFitModule of Thryve’s SDK. The module will allow your users to connect with Google Fit locally on their smartphone and will allow your app to trigger a background routine to retrieve both evaluated and aggregated values from different sources and sensors connected to Google Fit.

Google Fit Native: Constructor

Before calling any method of the Google Fit Native module, please create the corresponding corresponding GFitConnector.

import com.thryve.connector.module_gfit.GFitConnector

gfitConnector = new GFitConnector(context, requestedTypes)
Code Description
GFitConnector(activity: Activity, types: List? = null) Creates the GFitConnector object with given activity and type.

The Google Fit native integration through the Thryve SDK GFitModule will run as a service in the background. The first time the start() method is executed, a permission screen built-in the Android operating system will ask for the user's consent to grant access to the specified data types of Google Fit. The state of confirmation of this permission will be stored in the Android settings. The GFitModule methods need a Android Activity reference.

private fun toggleGFitIntegration() {
    if (!gFitConnector?.isActive()) {
        gFitConnector?.start(gFitPermissions) { response ->
            if (response.successful && response.data == true) {
                showMessage("GFit integration authorized and started")
            } else if (!response.successful && response.error != null) {
                showMessage("Error: ${response.error?.message}")
                gFitConnector?.stop() {
                    showMessage("GoogleFitModule stop result: ${it.data}")
                }
            } else {
                showMessage("GFit integration Unauthorized")
            }
        }
    } else {
        gFitConnector?.stop() {
            showMessage("GoogleFitModule stop result: ${it.data}")
        }
    }
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    gFitConnector?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    gFitConnector?.onActivityResult(requestCode, resultCode, data)
}

Additional details

Request Android Permissions for Google Fit

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

To use the native integration of Google Fit, your application needs to acquire the Android Permission ACTIVITY_RECOGNITION from your user to access data. Please add the code sample on the right to the manifest file. The SDK will request the permission when using the authorize method.

Initiate the Android WorkManager

class App : Application, Configuration.Provider {
    override fun getWorkManagerConfiguration() =
            Configuration.Builder()
                    .setMinimumLoggingLevel(Log.VERBOSE)
                    .build()

The scheduling behaviour of the synchronization service of the Google Fit Native SDK module requires the custom configuration and initialization of the Android WorkManager Make sure to use the WorkManagerInitializer in your Application class by implementing Configuration.Provider. Please refer to the Kotlin/Java code sample on the right side of the documentation for guidance.

Create the constructor object

Before calling any method of the GFitModule, please create the corresponding constructor object.

Code Description
GFitConnector(private val activity: Activity, private val types: List? = null) Creates the GFitConnector object.

Check if Google Fit is available on the device

We recommend to use the isAvailable at the beginning of every session before using any other methods to avoid errors. If Google Fit is not available all other methods will fail and result in errors.

Code Description
isAvailable: Boolean Checks if the device supports Google Fit. If the system app is not present on the device no data would be retrieved.

Check if Google Fit is already connected

The isActive method will check if the start method was called successfully and if the connection is still active. If the method returns false, you trigger the connection by using the start method. We recommend to use this method before using any method for data retrieval to avoid errors.

Code Description
fun isActive() Checks if Google Fit integration is active. Can be used for app internal logic or user feedback for GUIs etc.

Get user authorization

Before you can retrieve any data, your app needs to be authorized to access Google Fit data by your users. To get authorization, use the start method and the corresponding dialogue will be shown on top of your app.

When using start specify the data you want to access by listing the corresponding GFitDataType. Only if the user grants permission to access the data, any data retrieval can be performed.

Code Description
fun start(types: List, callback: (ThryveResponse<Boolean>) -> Unit) This method launches the Google Fit Native permission screen with the given requested types and starts the data retrieval.

The start method will first trigger the process to acquire the Android Permission ACTIVITY_RECOGNITION for your app. If the user accepts, the user will see an authorization page with the data types you specified and needs to grant permission. Make sure to store the result of the authorization process with the onRequestPermissionsResult and onActivityResult methods.

Code Description
fun onRequestPermissionsResult(params) This method will pass the parameters of the process of acquiring the Android Permission ACTIVITY_RECOGNITION to the connector object.
fun onActivityResult(params) This method will pass the parameters of the process of acquiring the specified GFitDataType to the connector object.

Check for authorization status

Google Fit Native allows developers to understand if the user has granted access to their health data and for what data types. We recommend to use this method before retrieving health data to check if the permissions are still active and to ensure permissions for the requested data types are granted.

Code Description
fun arePermissionsAcquired(): Boolean? Checks whether a user has granted permission to access one or more data types.
fun getAcquiredPermissions(): List? Returns a list (with 0 to N values) of data types the user has currently granted access to via the Shealth Permission Manager. Checks which permissions from the current permission set are considered acquired by the Shealth Permission Manager. If the permission check request failes, null will be returned.

If the method arePermissionsAcquired returns false or getAcquiredPermissions does not return a data type you want access to, please instruct your user to manually grant access in the Samsung Health app. This is needed as the permission screen dialogue can only be requested once for each data type.


Example of informing user about missing
authorization of GFitDataTypes

GoogleFit Native: Data retrieval

Disclaimer: unreliable/discrepant GoogleFit data:
Please acknowledge that data drawn from GoogleFit REST and/or GoogleFitNative can deviate considerably from the data shown in the GoogleFit app (e.g. up to 1000 steps difference). According to Google, it's due to the calculation engine that creates temporary differences. This has been a known issue and many clients are experiencing these persistent differences. Please refer to GoogleFit official reference for further details.

The Google Fit Native SDK module does not require to initiate the data retrieval. When the end-user has authorized data access, data can be drawn immediately. The module will fetch data from Google Fit until stop was called or the user revoked the authorization in the Google Fit app.

Code Description
fun stop(callback: (ThryveResponse<Boolean>) -> Unit) Stops the Google Fit native integration data retrieval and upload service. It is accompanied with a callback for further details. isActive() will return false aftwards.

Background data retrieval

The background retrieval of data from Google Fit will be started automatically when calling authorize successfully. No further action is required.

Manual data retrieval

To manually trigger the data retrieval, e.g., when a user clicks a button or every time the application is opened, use the synchroniseEpoch and synchroniseDaily method to retrieve the corresponding data types.

Code Description
fun synchroniseEpoch(types: List, callback: ((ThryveResponse<Boolean>) -> Unit)? = null)) Performs Epoch synchronization from last upload date to today. Call this function in order to synchronize epoch data immediately.
fun synchroniseEpoch(start: Date, end: Date, types: List, callback: ((ThryveResponse<Boolean>) -> Unit)? = null)) Performs Epoch synchronization between given dates, with a maximum of 30 days. If the difference is greater than 30 days, end date - 30 days is used as start date. Call this function in order to synchronize epoch data immediately.
fun synchroniseDaily(types: List) Performs Daily synchronization from last upload date to today. Call this function in order to synchronize daily data immediately.
fun synchroniseDaily(startDate: Date, endDate: Date, types: List) Performs Daily synchronization between given dates, with a maximum of 365 days. If difference is greater than 365 days, end date - 365 days is used as start date. Call this function in order to synchronize the daily data immediately.

Synchronize Methods Error Codes

Code Name Description
80001 ACCESS_TOKEN_INVALID No valid access token found. See Generate a Thryve user token.
80010 SYNC_START_AFTER_NOW the start date set in synchroniseEpoch or synchroniseDaily is set as a date that is in the future.
80011 SYNC_END_AFTER_NOW the end date set in synchroniseEpoch or synchroniseDaily is set as a date that is in the future.
80012 SYNC_END_BEFORE_START the end date set in synchroniseDaily or synchroniseDaily is set before the start date.

BGMModule (experimental): Constructor

The BGM module allows your users to connect their connected bloog glucose meters from the data sources i-Sens, B.Braun, and RocheAccuchek with your app via Bluetooth.

The module uses the Android classes BluetoothDevice and BluetoothGattCharacteristic that are wrapped inside the IBLE-interface that your underlying activity needs to implement. You must handover the activity itself to the BGMModule constructor as well.

public class BGMActivity extends AppCompatActivity implements IBLE {
  private BGMConnector bgmConnector;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bgmConnector = new BGMConnector(this, BGMDevice.BBRAUN);
    // [...]
  }

  @Override
  public void bleReady(@NotNull BluetoothGattCharacteristic racp) {
    bgmConnector.sync(racp);
  }

  @Override
  public void bleActivated(boolean isOn) {
    if(isOn) {
      bgmConnector.startScanning();
    }
  }

  @Override
  public void bleFound(@NotNull BluetoothDevice bluetoothDevice, int rssi) {
    bgmConnector.connect(bluetoothDevice);
  }

  @Override
  public void blePaired(@NotNull BluetoothDevice bluetoothDevice) {
    bgmConnector.disconnect();
  }

  @Override
  public void bleDisconnected(@NotNull BluetoothDevice bluetoothDevice) {}
}
Code Description
BGMConnector(AppCompatActivity activity, BGMDevice device) Creates the BGMConnector-object. Should be called from within an Android Activity. Parameters:

activity: Android AppCompatActivity activity
device: The device as defined in the BGMDevice Enum. Either ISENS, BBRAUN, or ROCHE_ACCUCHEK

We recommend initializing the BGMConnector-object inside your Android Activity class. This class also needs to implement the IBLE-interface. Please refer to the sample Java code on the right side of the documentation.

BGMModule (experimental): Scanning

To initially find your BGM device via Bluetooth, you need to start a scanning process that searches for nearby Bluetooth devices. You can perform this with the BGMConnector by using the following two methods:

Code Description
void startScanning() Starts the Bluetooth scanning process. This process runs indefinitely.
void stopScanning() Stops the Bluetooth scanning process. Does nothing, if it is not running.

The scanning process will not stop running, until it is stopped manually. Please ensure to implement proper Handlers, if you want to setup a timeout for device search.

BGMModule (experimental): Connection

When the scan finds one or more suitable devices, the IBLE-interface method bleFound(BluetoothDevice bluetoothDevice, int rssi) will be called, handing over the Android BluetoothDevice object. This device can either be stored temporarily for later connection or a connection to pair the device can directly be established.

Code Description
void connect(BluetoothDevice device) Connects to the given BluetoothDevice. Stores pairing information in the background. If a connection is active and paired the bleReady-method from IBLE interface will be called and data can be synchronized.
void disconnect() Disconnects the Bluetooth device. The pairing information stays valid.
void delete(BGMDevice device) Deletes the Bluetooth device by removing the pairing information as well.

BGMModule (experimental): Syncing

The synchronization process should be executed after the device has been successfully connected and the BluetoothGattCharacteristic has been handed over via the IBLE interface bleReady(BluetoothGattCharacteristic racp) method. The sync-method will perform the synchronization of recent BloodGlucose data in the background (up to one week, if the data has not been synchronized before) and will perform a direct upload to the Thryve data warehouse. When the upload succeeds, the disconnect of the BGMConnector will be executed automatically.

The method is structured as followed:

Code Description
void sync(BluetoothGattCharacteristic racp) Performs a background synchronization of the BloodGlucose data. A debug printout will be performed, if the synchronization was successful.

Integration for Web-Apps

The integration of Thryve into your web app does not require an SDK, but rather a collection of simple API-methods described in the next paragraphs. The methods allow to create a pseudonymous Thryve user token for your user and to allow your users to connect and disconnect 3rd party OAuth or direct access data sources. Please refer to the code snippets on the right side of the documentation for example implementations.

Generate a Thryve user

All data stored of any given end-user is linked to a pseudonymous Thryve user. This user is generated on backend side when calling the getAccessToken method. The method returns an accessToken, which is required for connecting data sources, uploading data or retrieving data for the user.

Additionally, you can set a unique identifier for the Thryve user. We call this the partnerUserID. Please ensure that the partnerUserID is an unguessable string generated e.g. through a hash-function. We suggest at least 32 digits, that may contain both digits, characters, and a dash „-„, as a special character.

To set this unique identifier, please add the partnerUserID when calling the getAccessToken method. If an accessToken is returned, you defined your user’s partnerUserID successfully.

curl --location --request POST -u'healthapp:A7qmaxf9a' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--data-urlencode'partnerUserID=FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk' --data-urlencode'language=en'\
'https://api.und-gesund.de/v5/accessToken'
HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/restjson/v5/accessToken");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write("partnerUserID=FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk&language=en");
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 200) {
    StringBuilder response = new StringBuilder();
    Reader inputStreamReader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
      response.append(line);
    }
    System.out.println(response.toString());
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/accessToken")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

let data = "partnerUserID=FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk&language=en"
request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 200 {
            print(String(data: data!, encoding: .utf8)!)
        }
    }
}
task.resume()
import json, requests, base64

headers = {
    'content-type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM')
}
params = {
  'partnerUserID': 'FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk',
  'language': 'en'
}

r = requests.post(
    'https://api.und-gesund.de/v5/accessToken',
    params = params,
    headers = headers
)

if r.status_code == 200:
    print r.text
$(function () {
  var formData = {
    partnerUserID: "FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk",
    language: "en",
  };

  $.ajax({
    url: "https://api.und-gesund.de/v5/accessToken",
    type: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
    },
    data: formData,
    statusCode: {
      200: function (data) {
        console.log(data.responseText);
      },
    },
  });
});
post
https://api.und-gesund.de/v5/accessToken
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
Query Parameter
PartnerUserID
optional
An optional customerID, which allows Thryve to persistently relate the accessToken to a user. If a customerID is provided, Thryve will return the last valid accessToken previously created for this user instead of generating a new one. Example structure: FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk.

Note: partnerUserID is only allowed to consist of alphanumeric characters, and a dash, "-", as a special character.
language
optional
Optionally determines the language setting for the corresponding user. Will be set as a string of the country code, e.g.: en. We currently support five languages: English, German, Spanish, French and Italian. If not set, the default partner language will be used.

Responses

Response Codes Description
200 Request successful
4xx error code


Response Parameter
accessToken Sample response: de3d1e068537dd927b48988cb6969abe

Sources connection

Having received the accessToken for your user, the following API call allows your user to connect their 3rd party devices via the data source connection screen. To give you a head-start we provide a ready-to-use website-URL for the data source connection screen that you can display e.g. as a Web view in your app – providing a seamless experience for your users.

The following interface returns a URL-String that can be used for your customer's data source connection.

curl --location --request POST -u'healthapp:A7qmaxf9a' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--data-urlencode'authenticationToken=de3d1e068537dd927b48988cb6969abe' \
'https://api.und-gesund.de/v5/dataSourceURL'
HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/v5/dataSourceURL");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write("authenticationToken=de3d1e068537dd927b48988cb6969abe");
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 200) {
    StringBuilder response = new StringBuilder();
    Reader inputStreamReader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
      response.append(line);
    }
    System.out.println(response.toString());
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/dataSourceURL")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

let data = "authenticationToken=de3d1e068537dd927b48988cb6969abe"
request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 200 {
            print(String(data: data!, encoding: .utf8)!)
        }
    }
}
task.resume()
import json, requests, base64

headers = {
    'content-type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM')
}
params = { 'authenticationToken': 'de3d1e068537dd927b48988cb6969abe' }

r = requests.post(
    'https://api.und-gesund.de/v5/dataSourceURL',
    params = params,
    headers = headers
)

if r.status_code == 200:
    print r.text
$(function () {
  var formData = {
    authenticationToken: "de3d1e068537dd927b48988cb6969abe",
  };

  $.ajax({
    url: "https://api.und-gesund.de/v5/dataSourceURL",
    type: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
    },
    data: formData,
    statusCode: {
      200: function (data) {
        console.log(data.responseText);
      },
    },
  });
});
post
https://api.und-gesund.de/v5/dataSourceURL
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
Query Parameter
authenticationToken
required
The Thryve acces token generated for your user. Example: de3d1e068537dd927b48988cb6969abe

Response example

https://service.und-gesund.de/dataSourceSelection.html?token=2098X4583882346015849835

Responses

Response Codes Description
200 Request successful
4xx error code

Custom data source connection

If you want your users to connect their data source through your own data source connection screen or other GUI, there is also a possibility to directly open the corresponding tracker connection or revoke page.

Since the redirect logic must be connected to our server routines, you will need to open the tracker connection page in the same window with a URL that needs to be constructed as described in this chapter. Moreover, to correctly come back to your website, you will need to provide a redirect URL.

To open the correct tracker connection page, you will need to provide the Thryve internal source ID.

Construct direct connection URL

Direct connection example URL

https://service.und-gesund.de/dataSourceDirectConnection.html?token=2098X4583882346015849835&dataSource=1

Direct revoke example URL

https://service.und-gesund.de/dataSourceDirectRevoke.html?token=2098X4583882346015849835&dataSource=1&direct=true

The direct connection URLs are based on the access of the dataSourceSelection page. Thus you will need to call the dataSourceURL-interface as described in the corresponding section above: Sources connection.

The result URL will contain a parameter with the key token. Example structure:
https://service.und-gesund.de/dataSourceSelection.html?token=2098X4583882346015849835

Since this token is the temporary authentication for the data sources, it is needed to perform a request to the direct connection URL as well.

For direct connection or revoke, you will have to exchange the html file like the following:

For addressing the correct connection page, the data source ID must be added with the URL-parameter dataSource. Please also refer to the data sources overview that also lists all source ID's. Example structure:
dataSource=1 (e.g. for Fitbit)

For the revoke call, you may also add another URL-parameter to directly get redirected to the revoke page of the corresponding source. Thus the Thryve confirmation page won't be shown beforehand. For this, just set the parameter direct to true. If set to false or not set at all, the confirmation page will be shown as usual. Example structure:
direct=true

Please refer to the code example on the right to see a full built URL. This URL can now be opened in any browser.

Parse result

Direct connection result example URL

https://service.und-gesund.de/dataSourceDirectConnectionResult.html?token=2098X4583882346015849835&dataSource=2&connected=true

After the user interaction, the Thryve server will automatically redirect to the page
dataSourceDirectConnectionResult.html.
The URL-parameter connected will now indicate, if the connection or revoke was successful. The following states can happen:

Please refer to the code example on the right to see a full result URL.

Handle redirect URL

Direct connection example URL

https://service.und-gesund.de/dataSourceDirectConnection.html?token=2098X4583882346015849835&dataSource=1&redirect_uri=https://example.com/result

Direct revoke example URL

https://service.und-gesund.de/dataSourceDirectRevoke.html?token=2098X4583882346015849835&dataSource=1&direct=true&redirect_uri=https://example.com/result

For a better user experience, you have also the possibility to set a redirect URL that will be used instead of the Thryve result page. This allows to seemlessly integrate into your web based application.

For this you will need to additionally set the URL-parameter redirect_uri for all direct connection calls. Example structure:
redirect_uri=https://example.com/result

The connected-result will also handed over to your URL.

Please refer to the code example on the right to see a full connection and revoke URL that contains the redirect URL as well.

PartnerDataUpload

The PartnerDataUpload allows you to upload custom data from the app to the Thryve data warehouse which is not data recorded by any data source. This might be a user’s demographic data like birthdate and gender or certain indications needed for health status calculation or other analytics of Thryve’s interpretation layer.

Data can be uploaded as DynamicEpochValues, DailyDynamicValue, or for slowly changing, long-term parameters as ConstantValues.

Please also refer to the sections Accessing the API and the Interpretation Layer of the data types overview.

While information about dynamicEpochValues DataTypes to be uploaded can be found in the Biomarkers page, the Additional Recording Information section explains the information related to "details" parameter, stated in the payload.

DynamicEpochValue

JSON Object String example

{
  "data": [
    {
      "value": "38.7",
      "startTimestamp": "2020-01-20T07:07:00+01:00",
      "endTimestamp": "2020-01-20T07:08:00+01:00",
      "dynamicValueType": 5041,
      "details": {
        "trustworthiness": "plausible",
        "medicalGrade": true,
        "userReliability": "confirmed",
        "timezoneOffset": 120
      }
    }
  ]
}
curl --location --request PUT -u'healthapp:A7qmaxf9a' --header'Content-Type:application/json' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--header'authenticationToken:de3d1e068537dd927b48988cb6969abe' \
--data-urlencode'@data.json' 'https://api.und-gesund.de/v5/dynamicEpochValue'
// JSON-String upload data, please refer to above example
// final String data = ...

HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/v5/dynamicEpochValue");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("PUT");
  connection.setRequestProperty("Content-Type", "application/json");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.setRequestProperty("authenticationToken", "de3d1e068537dd927b48988cb6969abe");
  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write(data);
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 204) {
    System.out.println("success");
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/dynamicEpochValue")!

// JSON-String upload data, please refer to above example
// let data = ...

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

request.setValue("de3d1e068537dd927b48988cb6969abe", forHTTPHeaderField: "authenticationToken")

request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 204 {
            print("success")
        }
    }
}
task.resume()
# JSON-String upload data, please refer to above example
# data = ...

headers = {
    'content-type': 'application/json',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM'),
    'authenticationToken': 'de3d1e068537dd927b48988cb6969abe'
}

r = requests.put(
    'https://api.und-gesund.de/v5/dynamicEpochValue',
    data = data,
    headers = headers
)

if r.status_code == 204:
    print 'success'
$(function () {
  // JSON-String upload data, please refer to above example
  // var data = ...

  $.ajax({
    url: "https://api.und-gesund.de/v5/dynamicEpochValue",
    type: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
      authenticationToken: "de3d1e068537dd927b48988cb6969abe",
    },
    data: data,
    statusCode: {
      204: function (data, textStatus, xhr) {
        console.log("success");
      },
    },
  });
});
PUT
https://api.und-gesund.de/v5/dynamicEpochValue
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
authenticationToken
required
The Thryve acces token generated for your user. Example: de3d1e068537dd927b48988cb6969abe
Query Parameter
[JSON Object String] JSON object, including the data array that contains objects. Please check the right column for the structure and an example.

While information about dynamicEpochValues DataTypes to be uploaded can be found in the Biomarkers page, the Additional Recording Information section explains the information related to "details" parameter, stated in the payload.

Responses

Response Codes Description
204 Upload successful
4xx error code

DailyDynamicValue

JSON Object String example

{
  "data": [
    {
      "day": "2019-01-01T00:00:00Z",
      "dailyDynamicValueType": 5020,
      "value": 70.5
    }
  ]
}
curl --location --request PUT -u'healthapp:A7qmaxf9a' --header'Content-Type:application/json' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--header'authenticationToken:de3d1e068537dd927b48988cb6969abe' \
--data-urlencode'@data.json' 'https://api.und-gesund.de/v5/dailyDynamicValues'
// JSON-String upload data, please refer to above example
// final String data = ...

HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/v5/dailyDynamicValues");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("PUT");
  connection.setRequestProperty("Content-Type", "application/json");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.setRequestProperty("authenticationToken", "de3d1e068537dd927b48988cb6969abe");
  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write(data);
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 204) {
    System.out.println("success");
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/dailyDynamicValues")!

// JSON-String upload data, please refer to above example
// let data = ...

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

request.setValue("de3d1e068537dd927b48988cb6969abe", forHTTPHeaderField: "authenticationToken")

request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 204 {
            print("success")
        }
    }
}
task.resume()
# JSON-String upload data, please refer to above example
# data = ...

headers = {
    'content-type': 'application/json',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM'),
    'authenticationToken': 'de3d1e068537dd927b48988cb6969abe'
}

r = requests.put(
    'https://api.und-gesund.de/v5/dailyDynamicValues',
    data = data,
    headers = headers
)

if r.status_code == 204:
    print 'success'
$(function () {
  // JSON-String upload data, please refer to above example
  // var data = ...

  $.ajax({
    url: "https://api.und-gesund.de/v5/dailyDynamicValues",
    type: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
      authenticationToken: "de3d1e068537dd927b48988cb6969abe",
    },
    data: data,
    statusCode: {
      204: function (data, textStatus, xhr) {
        console.log("success");
      },
    },
  });
});
PUT
https://api.und-gesund.de/v5/dailyDynamicValues
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
authenticationToken
required
The Thryve acces token generated for your user. Example: de3d1e068537dd927b48988cb6969abe
Query Parameter
[JSON Object String] JSON object, including the data array that contains objects. Please check the right column for the structure and an example.

Responses

Response Codes Description
204 Upload successful
4xx error code

ConstantValue

JSON Object String example

{
  "data": [
    {
      "dailyDynamicValueType": 9050,
      "value": 2
    }
  ]
}
curl --location --request PUT -u'healthapp:A7qmaxf9a' --header'Content-Type:application/json' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--header'authenticationToken:de3d1e068537dd927b48988cb6969abe' \
--data-urlencode'@data.json' 'https://api.und-gesund.de/v5/constantValue'
// JSON-String upload data, please refer to above example
// final String data = ...

HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/v5/constantValue");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("PUT");
  connection.setRequestProperty("Content-Type", "application/json");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.setRequestProperty("authenticationToken", "de3d1e068537dd927b48988cb6969abe");
  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write(data);
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 204) {
    System.out.println("success");
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/constantValue")!

// JSON-String upload data, please refer to above example
// let data = ...

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

request.setValue("de3d1e068537dd927b48988cb6969abe", forHTTPHeaderField: "authenticationToken")

request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 204 {
            print("success")
        }
    }
}
task.resume()
# JSON-String upload data, please refer to above example
# data = ...

headers = {
    'content-type': 'application/json',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM'),
    'authenticationToken': 'de3d1e068537dd927b48988cb6969abe'
}

r = requests.put(
    'https://api.und-gesund.de/v5/constantValue',
    data = data,
    headers = headers
)

if r.status_code == 204:
    print 'success'
$(function () {
  // JSON-String upload data, please refer to above example
  // var data = ...

  $.ajax({
    url: "https://api.und-gesund.de/v5/constantValue",
    type: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
      authenticationToken: "de3d1e068537dd927b48988cb6969abe",
    },
    data: data,
    statusCode: {
      204: function (data, textStatus, xhr) {
        console.log("success");
      },
    },
  });
});
PUT
https://api.und-gesund.de/v5/constantValue
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
authenticationToken
required
The Thryve acces token generated for your user. Example: de3d1e068537dd927b48988cb6969abe
Query Parameter
[JSON Object String] JSON object, including the data array that contains objects. Please check the right column for the structure and an example.

Responses

Response Codes Description
204 Upload successful
4xx error code

UserInformation

JSON Object String example

{
  "height": 192,
  "weight": 91,
  "birthdate": "1991-01-06",
  "gender": "male"
}
curl --location --request PUT -u'healthapp:A7qmaxf9a' --header'Content-Type:application/json' \
--header'AppAuthorization: Basic RkVoOUhRTmFhODdjd2RiQjpOTDduVGVnUG01REt0OExyQlpQNjJIUXo2Vk5aYUd1TQ==' \
--header'authenticationToken:de3d1e068537dd927b48988cb6969abe' \
--data-urlencode'@data.json' 'https://api.und-gesund.de/v5/userInformation'
// JSON-String upload data, please refer to above example
// final String data = ...

HttpURLConnection connection = null;
try {
  URL url = new URL("https://api.und-gesund.de/v5/userInformation");
  connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);

  connection.setRequestMethod("PUT");
  connection.setRequestProperty("Content-Type", "application/json");

  String authorization = new String(Base64.getEncoder().encode("healthapp:A7qmaxf9a".getBytes()));
  connection.setRequestProperty("Authorization", String.format("Basic %s", authorization));

  String appAuthorization = new String(Base64.getEncoder().encode("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM".getBytes()));
  connection.setRequestProperty("AppAuthorization", String.format("Basic %s", appAuthorization));

  connection.setRequestProperty("authenticationToken", "de3d1e068537dd927b48988cb6969abe");
  connection.connect();

  OutputStream outputStream = connection.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write(data);
  bufferedWriter.flush(); bufferedWriter.close(); outputStream.close();

  if(connection.getResponseCode() == 204) {
    System.out.println("success");
  }
} catch(IOException e) {
  e.printStackTrace();
} finally {
  if(connection != null) {
    connection.disconnect();
  }
}
let url = URL(string: "https://api.und-gesund.de/v5/userInformation")!

// JSON-String upload data, please refer to above example
// let data = ...

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let authCredentials = String("healthapp:A7qmaxf9a").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(authCredentials)", forHTTPHeaderField: "Authorization")

let appAuthCredentials = String("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM").data(using: String.Encoding.utf8)!.base64EncodedString()
request.setValue("Basic \(appAuthCredentials)", forHTTPHeaderField: "AppAuthorization")

request.setValue("de3d1e068537dd927b48988cb6969abe", forHTTPHeaderField: "authenticationToken")

request.httpBody = NSMutableData(data: String(data).data(using: String.Encoding.utf8)!) as Data

let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) {(data, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 204 {
            print("success")
        }
    }
}
task.resume()
# JSON-String upload data, please refer to above example
# data = ...

headers = {
    'content-type': 'application/json',
    'Authorization': 'Basic %s' % base64.b64encode('healthapp:A7qmaxf9a'),
    'AppAuthorization': 'Basic %s' % base64.b64encode('FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM'),
    'authenticationToken': 'de3d1e068537dd927b48988cb6969abe'
}

r = requests.put(
    'https://api.und-gesund.de/v5/userInformation',
    data = data,
    headers = headers
)

if r.status_code == 204:
    print 'success'
$(function () {
  // JSON-String upload data, please refer to above example
  // var data = ...

  $.ajax({
    url: "https://api.und-gesund.de/v5/userInformation",
    type: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Basic " + btoa("healthapp:A7qmaxf9a"),
      AppAuthorization:
        "Basic " + btoa("FEh9HQNaa87cwdbB:NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM"),
      authenticationToken: "de3d1e068537dd927b48988cb6969abe",
    },
    data: data,
    statusCode: {
      204: function (data, textStatus, xhr) {
        console.log("success");
      },
    },
  });
});
PUT
https://api.und-gesund.de/v5/userInformation
Header Parameter
Authorization
required
(Basic Auth) username:password
AppAuthorization
required
(Basic Auth) appID:appSecret
authenticationToken
required
The Thryve acces token generated for your user. Example: de3d1e068537dd927b48988cb6969abe
Query Parameter
height Height in centimeters.
weight Weight in kilograms.
birthdate Birth date in YYYY-MM-dd format.
gender Gender information as String (i.e. male, female, genderless)

Responses

Response Codes Description
204 Upload successful
4xx error code

Cross-Platform-Integration

Thryve maintains most parts of the SDK and Modules for Cross-Platform-Integrations based on ReactNative CLI and Flutter.

ReactNative

//Example integration in javascript
import React from "react";
import { StyleSheet, View, Text, Button } from "react-native";
import { Colors } from "react-native/Libraries/NewAppScreen";
import {
  getAccessToken,
  getDataSourceUrl,
  uploadConstantValue,
  uploadDailyDynamicValue,
} from "react-native-thryve-core-sdk-library";
import {
  isEnabled,
  isHealthKitAvailable,
  startHealthKitIntegration,
  stopHealthKitIntegration,
} from "react-native-thryve-module-apple-health-library";
import {
  isActive,
  isSHealthAvailable,
  startSHealthIntegration,
  stopSHealthIntegration,
} from "react-native-thryve-module-s-health-library";

const appId = "FEh9HQNaa87cwdbB";
const appSecret = "NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM";
const partnerUserId = "reactNativeAndroid";
const language = "en";

const App: () => React$Node = () => {
  return (
    <>
      <View>
        <Button
          onPress={() => {
            getAccessToken(
              appId,
              appSecret,
              partnerUserId,
              language,
              (error, event) => {}
            );
          }}
          title="Get Access Token"
        />
        <Text style={styles.welcome}>iOS ONLY</Text>
        <Button
          onPress={() => {
            startHealthKitIntegration((error, event) => {});
          }}
          title="Start HealthKit integration"
        />
        <Button
          onPress={() => {
            stopHealthKitIntegration((error, event) => {});
          }}
          title="Stop HealthKit integration"
        />
        <Text style={styles.welcome}>Android ONLY</Text>
        <Button
          onPress={() => {
            startSHealthIntegration((error, event) => {});
          }}
          title="Start SHealth integration"
        />
        <Button
          onPress={() => {
            stopSHealthIntegration((error, event) => {});
          }}
          title="Stop SHealth integration"
        />
      </View>
    </>
  );
};
export default App;

Developing ReactNative applications with the ReactNative CLI will result into projects that are usually deployed with Android Studio or Xcode for iOS. Please refer to the direct integration chapters for making use of the Thryve SDKs and modules:

   "dependencies": {
    "react-native-thryve-core-sdk-library": "file:../react-native-thryve-core-sdk-library",
    "react-native-thryve-module-apple-health-library": "file:../react-native-thryve-module-apple-health-library",
    "react-native-thryve-module-commons-library": "file:../react-native-thryve-module-commons-library",
    "react-native-thryve-module-s-health-library": "file:../react-native-thryve-module-s-health-library",
    "react": "17.0.2",
    "react-native": "^0.66.0",
  },
  "devDependencies": {
    "@types/react": "^18.0.9",
    "@types/react-native": "0.66.0",
},

Example of AppleHealth initialization in Objective-C

- (instancetype)init
{
    self = [super init];
    if (self) {
        /// Add additional types here
        types = [NSSet setWithObjects:
                 HKConnectorType.dateOfBirth,
                 HKConnectorType.height,
                 HKConnectorType.stepCount,
                 HKConnectorType.heartRate,
                 HKConnectorType.restingHeartRate,
                 HKConnectorType.sleepAnalysis,
                 nil];
    }
    return self;
}

To integrate the React native SDK please follow the next few steps

Example of SHealth initialization in Java

    public ThryveModuleSHealthLibraryModule(ReactApplicationContext reactContext)
    {
        super(reactContext);
        this.reactContext = reactContext;
        this.mTypeList = new ArrayList<>();
        /*
         * Add data types here
         */
        mTypeList.add(SHealthDataType.STEP_COUNT);
        mTypeList.add(SHealthDataType.SLEEP);
        mTypeList.add(SHealthDataType.SLEEP_STAGE);
        mTypeList.add(SHealthDataType.HEART_RATE);
    }



Flutter

Developing Flutter applications with the Flutter SDK will result into projects that can be deployed with Android Studio or Xcode for iOS. Please refer to the direct integration chapters for a walk-through of the Thryve SDKs and modules:

Example of CoreSDK integration in Dart

class CoreService {
  CoreSdk _coreSdk;

  CoreService({String partnerUserId = 'Dart'}) {
    _coreSdk = CoreSdk(
        appId: 'FEh9HQNaa87cwdbB',
        appSecret: 'NL7nTegPm5DKt8LrBZP62HQz6VNZaGuM',
        partnerUserId: partnerUserId,
        language: 'en');
  }

  Future<String> getAccessToken() async => await _coreSdk.getAccessToken();
}

class YourWidget extends StatelessWidget {
    ...
    @override
    Widget build(BuildContext context) {
      return Container(
        child: FlatButton(
          onPressed: () async {
            final CoreService service = CoreService("FVMW6fp9wnUxKnfekrQduZ96Xt6gemVk");
            final accessToken = await service.getAccessToken();
          }),
        ),
      );
    }
    ...
}

Please refer to our Flutter Sample App for example implementations of the different modules.

To integrate the Flutter SDK please follow the next few steps

All available functions derive from the native SDK's:

The bridging between iOS and Android native code and Dart VM is already implemented appropriately for each platform. For better integration of functions related to get values like UserInformation the plugin already contains data modules inside the model package.