Link Search Menu Expand Document
Developer | Sahha

SDK

Learn how to use the Sahha SDK in your Android app.


Table of contents
  1. Repository
  2. Installation
    1. Step 1) Add Jitpack
    2. Step 2) Add Implementation
    3. Step 3) Add Permissions
    4. Step 4) Import Module
  3. Configure
    1. Environment Settings
    2. Custom Notification Icon
    3. Custom Notification Settings
    4. Default Notification Settings
    5. Sensor Settings
    6. Sensor Data Settings
  4. Profile
    1. Authenticate
    2. Demographic
  5. Sensors
    1. Sensor Status
    2. Enable Sensors
    3. Open App Settings
    4. Post Sensor Data
  6. Analyze

Repository

You can browse the Sahha Android SDK on Github.

Android SDK [Github]


Installation

Step 1) Add Jitpack

Add the Jitpack repository to your project’s Settings.gradle.

Settings.gradle

repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

Step 2) Add Implementation

Add the Sahha SDK implementation to your project’s dependencies in Build.gradle.

Build.gradle

dependencies {

    ...

    implementation 'com.github.sahha-ai:sahha-android:+'

    ...

}

Step 3) Add Permissions

Add the required permissions to your project’s AndroidManifest.xml.

AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

Step 4) Import Module

Import the Sahha module into any files inside your project that use the SDK.

Kotlin

import sdk.sahha.android.source.*

Configure

The Sahha SDK must be configured immediately on app launch. We suggest you configure Sahha inside onCreate of your app’s MainActivity.

You may pass an optional list of settings to the configure method.

MainActivity.kt

import sdk.sahha.android.source.*

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // You can specify optional custom notification settings
        val notificationSettings = SahhaNotificationConfiguration(
            icon = R.drawable.ic_test, // The icon id must match the filename you add to the project
            title = "Custom Title",
            shortDescription = "Custom description",
        )

        val settings = SahhaSettings (
            environment = SahhaEnvironment.development,
            notificationSettings = notificationSettings, // Optional, defaults to null
            sensors = [.pedometer, .sleep], // Optional, defaults to all avaialable sensors
            postSensorDataManually = false, // Optional, defaults to false
        )

        Sahha.configure(application, settings) { error, success ->
            if (error != null) {
                println(error)
            } else {
                println(success.toString())
            }
        }
    }
}

Environment Settings

The SahhaEnvironment determines if the SDK connects to the development or production server of the API. Setting this incorrectly will send data to the wrong server.

SahhaEnvironment Description
development For development and testing
production For submission to the App store
enum class SahhaEnvironment {
    development,
    production
}

Custom Notification Icon

You can add an optional custom notification icon to your app.

More information regarding supported image types can be found here: Create app icons with Image Asset Studio

Step 1) Open your project in Android Studio.

Step 2) With the app folder highlighted, selectFileNewImage Asset.

Step 3) Select Notification Icons for Icon Type, enter a Name, select Image as Asset Type and alter the Padding as desired.

Step 4) This page can typically be left as it is. Select Finish.


Custom Notification Settings

You can specify optional custom notificationSettings. If notificationSettings are not specified, then the app will use the default notification settings.

val notificationSettings = SahhaNotificationConfiguration(
    icon = R.drawable.ic_test, // The icon id must match the filename you add to the project
    title = "Custom Title",
    shortDescription = "Custom description",
)

Default Notification Settings

If custom notificationSettings are not specified, then the app will use the default notification settings. If custom notificationSettings are only partially specified, then the app will use the default notification settings.The app will fill in the missing notification parameters with default values. E.g. if an icon and title are provided but a shortDescription is not, then the shortDescription will use the default value.

val icon = R.drawable.ic_sahha_no_bg // The Sahha logo
val title = "Analytics are running"
val shortDescription = "Swipe for options to hide this notification."

Sensor Settings

You can specify which sensors for the Sahha SDK to use. To optimize your analysis result, we suggest enabling all sensors. Leave this value null to enable all sensors by default.

Some sensors are not available on all platforms.

SahhaSensor Description Android iOS
device For tracking device usage patterns X
sleep For tracking sleep patterns
pedometer For tracking walking patterns
enum class SahhaSensor {
    device,
    sleep,
    pedometer
}

Sensor Data Settings

If you would like to handle posting of sensor data to the Sahha API manually, set postSensorDataManually to true. You will then need to post sensor data to the Sahha API manually by calling postSensorData.

If you would like the Sahha SDK to handle posting of sensor data to the Sahha API automatically, set postSensorDataManually to false.

postSensorDataManually defaults to false.

postSensorDataManually Description
true You will post sensor data to the Sahha API manually by calling postSensorData
false The Sahha SDK will post sensor data to the Sahha API automatically

Profile

Each user of your app will be assigned a Sahha Profile for analyzation. This is not handled by the Sahha SDK. Please refer to the separate Sahha API documentation for steps to generate profiles and profile tokens.

Authenticate

The Sahha SDK must be authenticated in order to connect to the Sahha API. Do this once per user profile. Once the user is successfully authenticated, the SDK will take care of automatically refreshing expired tokens.

Sahha.authenticate(profileToken: "PROFILE_TOKEN", refreshToken:  "REFRESH_TOKEN") { error, success ->
    if (success) greeting = "Successful"
    else greeting = error ?: "Failed"
}

Demographic

Each authenticated profile includes an optional demographic which can be used to increase the accuracy of analyzation. This data is not collected automatically. Your app can choose to GET or POST this demographic to the Sahha API.

All values are optional. String values are case insensitive (for example: 'us' and 'US' are equal and valid).

age : Int

Age must be a valid Int between 1 - 99.

gender : String

Gender must be a valid String from this list:

  • 'male'
  • 'female'
  • 'gender diverse'

country : String

Country must be a valid 2 character ISO String from this list:

ISO Country Codes

birthCountry : String

Birth Country must be a valid 2 character ISO String from this list:

ISO Country Codes

ethnicity : String

Any String value.

occupation : String

Any String value.

industry : String

Any String value.

incomeRange : String

Any String value.

education : String

Any String value.

relationship : String

Any String value.

locale : String

Any String value.

livingArrangement : String

Any String value.

birthDate : String

Birth Date must be a String in the format 'YYYY-MM-DD'. For example, '1990-05-20'.

MODEL

class SahhaDemographic {
    public var age: Int?
    public var gender: String? // "male", "female", "gender diverse"
    public var country: String? // ISO 2 character code, i.e. "us", "uk", "au", etc.
    public var birthCountry: String?  // ISO 2 character code, i.e. "us", "uk", "au", etc.
    public var ethnicity: String? // any string
    public var occupation: String? // any string
    public var industry: String? // any string
    public var incomeRange: String? // any string
    public var education: String? // any string
    public var relationship: String? // any string
    public var locale: String? // any string
    public var livingArrangement: String? // any string
    public var birthDate: String? // must be in format "YYYY-MM-DD", i.e. "1990-05-20"
}

POST

var demographic = SahhaDemographic(age: 21, gender: "female", country: "uk", birthCountry: "au")

Sahha.postDemographic(demographic) { error, success ->
    if (error != null) {
        println(error)
    } else {
        println(success.toString())
    }
}

GET

Sahha.getDemographic() { error, demographic ->
    if (error != null) {
        println(error)
    } else if (demographic != null) {
        println(demographic)
    }
}

Sensors

The Sahha SDK acts as a bridge between your app and the device sensors.


Sensor Status

The sensors have multiple possible statuses.

enum class SahhaSensorStatus {
    pending, /// Sensors pending User permission
    unavailable, /// Sensors not supported by the User's device
    disabled, /// Sensors disabled by the User
    enabled /// Sensors enabled by the User
}

You can check the current status of the sensors by calling getSensorStatus. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

Sahha.getSensorStatus(this@MainActivity) { error, sensorStatus ->
    if (error != null) {
        println(error)
    } else {
        println(sensorStatus.name)
    }
});

Enable Sensors

Before the SDK can start collecting data, you will need to enable sensors by calling enableSensors. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

Sahha.enableSensors(this@MainActivity) { error, sensorStatus ->
    if (error != null) {
        println(error)
    } else {
        println(sensorStatus.name)
    }
}

Open App Settings

It’s possible for your app user to disable a sensor. In this case, you must send the user to the app settings to manually enable the sensor.

Sahha.openAppSettings(this@MainActivity)

Post Sensor Data

By default, the Sahha SDK will post sensor data automatically. However, if you set postSensorDataManually to true, you will need to post sensor data manutally to the Sahha API by calling postSensorData at a regular interval of your choosing.

Sahha.postSensorData { error, success ->
    if (success) manualPost = "Successful"
    else manualPost = error ?: "Failed"
}

Analyze

You can analyze a user’s activities over a period of time and receive a mental health personalized report which you can display or action within your app. The default time period for an analysis is the previous 24 hours.

You can set (includeSourceData: true) if you would like to receive an array of the source data that was used to generate the analysis in the response. The default value is false.

// Analyze previous 24 hours
// Leave date range empty

Sahha.analyze(true) { error, success ->
    error?.also {
        println(error)
    }
    success?.also {
        println(success)
    }
}

You can provide an optional data range if you would like to receive multiple analysis over a specific time period. The response will include an array of analysis for each 24 hour segment in that time period.

// Analyze Previous 7 Days
// Add a date range

val now = Date()
val lastWeek = Date(now.time - SEVEN_DAYS_MILLIS)

Sahha.analyze(
    true,
    Pair(lastWeek, now)
) { error, success ->
    error?.also {
        println(error)
    }
    success?.also {
        println(success)
    }
}

The response will be in JSON format. An example response includes these fields:

{
  "inferences": [
    {
      "createdAt": "2022-05-20T00:30:00+00:00",
      "predictionState": "not_depressed",
      "predictionSubState": "",
      "predictionRange": -1,
      "predictionConfidence": 0.8,
      "dataSource": ["sleep", "screenTime"]
    }
  ]
}

The analysis engine requires a minimum amount of device sensor data to be uploaded and processed before an analysis can be determined. If you call analyze for a new user profile, it’s possible for the response to be 204 No Content. This is not an error. You will need to wait and try again every 24 hours until an analysis is available.

// An analysis is not ready yet
// Try again in 24 hours
// Empty JSON
{}