website logo
⌘K
Quickstart
User
Metrics
Webhooks
Mobile SDK
V2
React Native
Flutter
Android (Kotlin)
Swift
V1
Errors
FAQ
Docs powered by
Archbee
Mobile SDK
V2

Android (Kotlin)

Spike Android SDK is a library on top of Android HealthConnect that

  1. helps with the extraction of data.
  2. pushes data to SpikeAPI and delivers standardized data.

Do note, that according to Google's specification, you should only use SDK while the consuming app is in the foreground. Please make sure that you follow the advice shown here before releasing the app to production, especially the mandatory declaration.

  • Android 9.0+

Installation

To add the SDK to your project, you have to add the following to your project's build.gradle file in the repositories block.

JS
|
allprojects {
    repositories {
        // Other repositories
        maven {
            url 'https://gitlab.com/api/v4/projects/43396247/packages/maven'
        }
    }
}



After that, you have to add the following to your app's build.gradle file in the dependencies block.

build.gradle
|
dependencies {
    // Other dependencies
    implementation "com.spikeapi.sdk:spike-sdk-core:1.1.8"
}


Getting Started

First of all, you have to add the required health permissions to your AndroidManifest.xml. That allows you to fully utilize Spike SDK and to read the necessary data from apps that integrate with HealthConnect.

AndroidManifest
|
<manifest>
    <uses-permission android:name="android.permission.health.READ_NUTRITION"/>
    <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
    <uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED"/>
    <uses-permission android:name="android.permission.health.READ_STEPS"/>
    <uses-permission android:name="android.permission.health.READ_DISTANCE"/>
    <uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED"/>
    <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE"/>
    <uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY"/>
    <uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED"/>
    <uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE"/>
    <uses-permission android:name="android.permission.health.READ_SLEEP"/>
    <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
    <uses-permission android:name="android.permission.health.READ_EXERCISE"/>
    <uses-permission android:name="android.permission.health.READ_SPEED"/>
    <uses-permission android:name="android.permission.health.READ_POWER"/>
    <uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION"/>
    <uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE"/>
    <uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE"/>
    <uses-permission android:name="android.permission.health.READ_WEIGHT"/>
    <uses-permission android:name="android.permission.health.READ_HEIGHT"/>
    <uses-permission android:name="android.permission.health.READ_BODY_FAT"/>
    <uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS"/>
    <uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS"/>
    <uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE"/>
    <uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE"/>
    <uses-permission android:name="android.permission.health.READ_BONE_MASS"/>
</manifest>


As well as you have to add an intent filter to your activity definition so that you can request the permissions at runtime.

XML
|
<intent-filter>
    <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>


Configuration

Kotlin
|
// Prepare your API credentials
// APP ID and APP TOKEN from Spike developer console
private const val CLIENT_ID = "32485ab8-fb08-4c24-bac9-20dadsads1107"
private const val AUTH_TOKEN = "aadaa48-33a6-4040-9a88-60eddae3f1e9"

// Your webhook address where transformed data should be delivered
private const val CALLBACK_URL = "your.callback.url"

// Your webhook address where transformed data should be delivered
private const val END_USER_ID = "user-123"

// Create a Spike object via setup function
spikeConnection = SpikeWebhookConnection.createConnection(
    context = context,
    authToken = AUTH_TOKEN,
    appId = CLIENT_ID,
    customerEndUserId = END_USER_ID,
    callbackUrl = CALLBACK_URL,
    logger = Logger()
)

// Retrieve the permissions set and request access via your preferred method. An example in a composable
val permissions = spikeConnection.getRequiredHealthPermissionsMetadata()
val onPermissionsResult = {
    // Do something when permissions are received
}
val permissionsLauncher =
    rememberLauncherForActivityResult(spikeConnection.requestReadAuthorization()) {
        onPermissionsResult()
    }
permissionsLauncher.launch(permissions)

// You can check if all permissions were granted
val allPermissionsGranted = spikeConnection.hasHealthPermissionsGranted()

// You can manage all permissions and enable what was not enabled
spikeConnection.manageHealthConnect()

// You can check whether HealthConnect is available on the device
val healthConnectAvailability = spikeConnection.getHealthConnectAvailability()

// You can also revoke all permissions in one go if the user wants to
spikeConnection.revokeAllPermissions()


Getting and using data

Kotlin
|
// Read your preferred data

// Get data for a data type
val extractedData = spikeConnection.extractData(dataType)

// Get data for a data type for a specific date range
val extractedData = spikeConnection.extractData(dataType, from, to)

// Get data and post it for a data type
val webhookJob = spikeConnection.extractAndPostData(dataType)

// Get data and post it for a data type for a specific date range
val webhookJob = spikeConnection.extractAndPostData(dataType, from, to)

// Data types are defined in SpikeDataTypes class

// Interact with the connection object

// You can close the connection, which makes it unusable after the fact
spikeConnection.close()

// You can pack your connection data into a encrypted string and store it for later use
val packedConnection = spikeConnection.pack()

// After you have packed your connection, you can unpack it and use it again
val spikeConnection = SpikeConnection.unpackConnection(packedConnection)

// You can retrieve the connection app id
val appId = spikeConnection.getAppId()

// You can retrieve the connection spike user id
val spikeUserId = spikeConnection.getSpikeUserId()

// You can retrieve the connection customer end user id
val customerEndUserId = spikeConnection.getCustomerEndUserId()

// You can retrieve the callback url
val callbackUrl = spikeConnection.getPostbackUrl()


Logging

Internally, the Android SDK supports logging on various levels to assist with troubleshooting. However, the SDK expects a concrete logging implementation to be provided externally to avoid imposing additional third-party dependencies on library users. This can be done by implementing the SpikeLogger class and providing it when creating or unpacking a connection.

Below is an example of how to implement a simple console logger.

Kotlin
|
// You can log events to the logger for easier debugging

// Log an event
logger.debug("Event information")

// To be able to use the logger, you have to implement the SpikeLogger interface and pass it in on connection creation
// An example implementation
class Logger : SpikeLogger {
    override fun debug(message: String) {
        Log.d("SpikeLogger", message)
    }
    
    // omitted code
}



Data types

SpikeDataTypes.activitiesStream SpikeDataTypes.activitiesSummary SpikeDataTypes.breathing SpikeDataTypes.calories SpikeDataTypes.distance

SpikeDataTypes.glucose SpikeDataTypes.heart SpikeDataTypes.oxygenSaturation SpikeDataTypes.sleep SpikeDataTypes.steps

Classes

Spike

Class

Method

Description

Spike

createConnection

Creates a new SpikeConnection instance with the given user details.

Parameters: appId, authToken, customerEndUserId, logger

Returns: An instance of the SpikeConnection class.

Spike

createConnection

Creates a new connection instance with the given user details that is capable of delivering data to the customer backend via webhooks.

Parameters: appId, authToken, customerEndUserId, callbackUrl, logger

Returns: An instance of the SpikeWebhookConnection class.

Spike

unpackConnection

Restores a connection instance from a previously serialised state. A connection cannot be unpacked if a strong reference to a connection with the same session ID already exists.

Parameters: connection, logger

Returns: An instance of the SpikeConnection or SpikeWebhookConnection class. The method return type should be that of a base class, i.e., SpikeConnection.

Spike

ensurePermissionsAreGranted

Verifies that platform-specific permissions corresponding to the Spike data types provided are granted. In the event that some permissions are not granted, a platform-specific permissions dialogue will be presented to the end-user.

This method should only be invoked from a UI component

Parameters: permissions (Set<SpikeDataType>)

SpikeConnection

Class

Method

Description

SpikeConnection

getAppId

Retrieves the unique Spike application identifier.

Returns: string

SpikeConnection

getSpikeEndUserId

Retrieves the unique identifier assigned to the end-user by Spike.

Returns: string

SpikeConnection

getCustomerEndUserId

Retrieves the unique identifier assigned to the end-user by the customer.

Returns: string

SpikeConnection

close

Terminates any ongoing connections with Spike’s backend servers, clears any caches, and removes provided user details and tokens from the memory. Once the connection is closed, it cannot be used, and any method other than close() will throw a SpikeConnectionIsClosed exception.

SpikeConnection

extractData

Extracts local device data for the current date in the end-user’s time zone.

Parameters: dataType(SpikeDataType)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeConnection

extractData

Extracts local device data for the given time range. The maximum allowed single-query time interval is 7 days. If required, data of any longer time period can be accessed by iterating multiple queries of 7 days.

Parameters: dataType(SpikeDataType), from(DateTime), to(DateTime)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeConnection

pack

Creates a string representation of the connection state. This method facilitates the persistence of connections.

Returns: String

SpikeWebhookConnection

Class

Method

Description

SpikeWebhookConnection

getAppId

Retrieves the unique Spike application identifier.

Returns: string

SpikeWebhookConnection

getSpikeEndUserId

Retrieves the unique identifier assigned to the end-user by Spike.

Returns: string

SpikeWebhookConnection

getCustomerEndUserId

Retrieves the unique identifier assigned to the end-user by the customer.

Returns: string

SpikeWebhookConnection

getCallbackUrl

Returns the URL that will receive webhook notifications.

SpikeWebhookConnection

close

Terminates any ongoing connections with Spike’s backend servers, clears any caches, and removes provided user details and tokens from the memory. Once the connection is closed, it cannot be used, and any method other than close() will throw a SpikeConnectionIsClosed exception.

SpikeWebhookConnection

extractData

Extracts local device data for the current date in the end-user’s time zone.

Parameters: dataType(SpikeDataType)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeWebhookConnection

extractData

Extracts local device data for the given time range. The maximum allowed single-query time interval is 7 days. If required, data of any longer time period can be accessed by iterating multiple queries of 7 days.

Parameters: dataType(SpikeDataType), from(DateTime), to(DateTime)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeWebhookConnection

extractAndPostData

Extracts local device data for the current date in the local user time zone and sends it as a webhook notification to the customer’s backend.

Parameters: dataType(SpikeDataType)

SpikeWebhookConnection

extractAndPostData

Extracts local device data for the given time range and sends it as a webhook notification to the customer’s backend.

Parameters: dataType(SpikeDataType), from(DateTime),

to(DateTime)

SpikeWebhookConnection

enableBackgroundDelivery

Enables background data delivery for selected data types. No-op on Android (for now).

Parameters: dataType(SpikeDataType)

SpikeWebhookConnection

pack

Creates a string representation of the connection state. This method facilitates the persistence of connections.

Returns: String

Errors and Exceptions

SpikeException

The abstract parent of all concrete exceptions.

SpikeConnectionAlreadyExistsException

Thrown if an attempt to unpack a Spike connection is made while a strong reference to the same connection already exists.

SpikeConnectionIsClosedException

Thrown if any method is invoked on SpikeConnection or one of its subclasses after the connection has been closed.

SpikeInvalidCredentialsException

Thrown if the credentials provided are not recognised, i.e. are invalid or expired.

SpikeInvalidDateRangeException

Thrown if duration exceeds the allowed maximum or if ‘from’ date is greater than ‘to’ date. The message will contain a specific cause description.

SpikeInvalidCallbackUrlException

Thrown if the callback URL is not a valid URL, does not have HTTPS schema, or is not a sub-URL of the main callback URL configured for the application. The exception message will contain a specific reason.

SpikePackException

Thrown when a connection cannot be serialised to a packed state. The exception cause will contain the underlying error.

SpikePermissionsNotGrantedException

Thrown when Spike SDK is unable to access the data due to permissions not being granted.

SpikeServerException

Whenever any operation with the Spike backend fails and the error does not fall into any of the above exceptions. The exception cause will contain the underlying error.

SpikeUnpackException

Thrown when a connection cannot be deserialised from a packed state. The exception cause will contain the underlying error.

Did this page help you?
PREVIOUS
Flutter
NEXT
Swift
Docs powered by
Archbee
TABLE OF CONTENTS
Installation
Getting Started
Configuration
Getting and using data
Logging
Data types
Classes
Spike
SpikeConnection
SpikeWebhookConnection
Errors and Exceptions
SpikeException
SpikeConnectionAlreadyExistsException
SpikeConnectionIsClosedException
SpikeInvalidCredentialsException
SpikeInvalidDateRangeException
SpikeInvalidCallbackUrlException
SpikePackException
SpikePermissionsNotGrantedException
SpikeServerException
SpikeUnpackException
Docs powered by
Archbee