Quickstart (Android)

The Roam Android SDK makes it quick and easy to build a location tracker for your Android app. We provide powerful and customizable tracking modes and features.

Requirements

To use the Roam SDK,

  • Get yourself a free Roam Account. No credit card is required.

  • Create a project and add an Android app to the project.

  • You need the PUBLISHABLE_KEY (available in your project settings) to initialize the SDK.

Now, you’re ready to integrate the SDK into your Android application.

Roam Android SDK requires Android Studio 2.0 or later and is compatible with apps targeting Android SDK Version 16 or above.

Run the example application

The Roam Example repository on GitHub includes sample applications that demonstrate the use of the v3 Roam SDK for Android.

To run an example app, clone this repository, navigate to the example app in paths Example/ , add your publishable YOUR-PUBLISHABLE-KEY key in MainApplication.java, and run the app.

Make sure the package name is the same as the one registered on our Roam dashboard.

Android Studio Setup

To use the Android SDK in a project, add the SDK as a build dependency and sync the project.

  1. Go to Android Studio > New Project > Minimum SDK

  2. Select API 16: Android 4.1.0 (Jelly Bean) or higher and create a project

  3. After you create a new project, open Gradle Scripts > build.gradle (Project: <your_project>) and do the following:

    1. Add the following to the build script {repositories {}} section of the build.gradle (Project)file:

      mavenCentral()

Sync and close build.gradle (Project: <your_project>)

SDK Installation

Gradle Installation

To install the SDK for your project via Gradle in Android Studio, add the maven below to your project build.gradle file.

repositories {
    maven {
        url 'https://com-roam-android.s3.amazonaws.com/'
    }
}

add the dependencies below to your app build.gradle file.

dependencies {
 implementation 'com.roam.sdk:roam-android:0.1.20'
}

Then sync Gradle.

Manual Installation

Download and unzip the Roam SDK.

  1. Open Android Studio and add the SDK Roam.aar as a module using File > New > New Module > Import .JAR/.AAR Package.

  2. Once Gradle is finished, click File > Project Structure again.

  3. Click on the Dependencies tab > click App > click the “+” icon in the top left of the Declared Dependencies section > select Module Dependency > click on Roam-release > press Ok and wait for Gradle to sync again.

  4. Make sure to include the dependencies separately and sync your project.

dependencies {
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.4'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
}

Initialize the SDK

Roam SDK offers a flexible method of initialization, allowing developers to seamlessly integrate our services into their applications. With our latest update, we've introduced a new initialization approach using Manifest file. This method provides an effortless way to set up your Roam SDK without the need for additional code.

Using Manifest file Initialization:

  1. Optional Parameter: Publish Key

    • The publishKey parameter in the initialization method is now optional.

    • If you've added your Roam publish key to your project's Manifest file, there's no need to pass the publishKey parameter during initialization.

  2. Configure Your Manifest File:

    • In your Manifest file, declare your Roam publish key as follows:

    <meta-data
     android:name="com.roam.lib.sdk.PUBLISH_KEY"
     android:value="${ROAM_PUBLISH_KEY}" />
    • Replace ${ROAM_PUBLISH_KEY} with your actual Roam publish key.

  3. Using local.properties (Optional):

    • Alternatively, you can use a local.properties file to feed the Roam publish key to the Manifest file.

    • In your local.properties file, add the following line, replacing XXXXXXXXXXXXXX with your Roam publish key:

    ROAM_PUBLISH_KEY = XXXXXXXXXXXXXX
    • To get Roam publish key from local.properties to Manifest, user must have to add following code in build.gradle(app)

    defaultConfig {
            Properties properties = new Properties()
            properties.load(project.rootProject.file('local.properties').newDataInputStream())
            manifestPlaceholders = [ROAM_PUBLISH_KEY: "${properties.getProperty('ROAM_PUBLISH_KEY')}"]
    
        }
  4. Initialization Code:

    • Initialize Roam SDK in your application class as follows:

    • If the publish key is added to the Manifest file, the initialize method can be called without passing the publishable key.

Roam.initialize(this)

By following these steps, you can seamlessly initialize Roam SDK using manifest file, simplifying the integration process and saving valuable development time.

Using Application class Initialization:

Before initializing the SDK, the below must be imported.

import com.roam.sdk.Roam;

After importing, add the code below under the Application class onCreate() method. The SDK must be initialized before calling any of the other SDK methods.

Roam.initialize(this, "YOUR-SDK-KEY-GOES-HERE")

Request Permission

To request the location for devices running both below/above Android 10, refer to the following piece of code.

if (!Roam.checkLocationServices()) {
	Roam.requestLocationServices(this)
} else if (!Roam.checkLocationPermission()) {
	Roam.requestLocationPermission(this)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Roam.checkBackgroundLocationPermission()) {
	Roam.requestBackgroundLocationPermission(this)
}

Location Tracking

Start Tracking

Roam.startTracking(TrackingMode, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })

Specify the tracking modes while you use the Roam.startTrackingmethod.

Tracking Modes

Adaptive Tracking

Roam has three default tracking modes along with a custom version. They differ based on the frequency of location updates and battery consumption. The higher the frequency, the higher the battery consumption. You must use the foreground service for continuous tracking.

Mode

Battery usage

Updates every

Optimized for/advised for

Active

6% - 12%

25 ~ 250 meters

Ride Hailing / Sharing

Balanced

3% - 6%

50 ~ 500 meters

On Demand Services

Passive

0% - 1%

100 ~ 1000 meters

Social Apps

// active tracking
Roam.startTracking(RoamTrackingMode.ACTIVE, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })
// balanced tracking
Roam.startTracking(RoamTrackingMode.BALANCED, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })
// passive tracking
Roam.startTracking(RoamTrackingMode.PASSIVE, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })

Distance Interval Tracking

The SDK also provides a custom tracking mode that allows you to customize and build your own tracking modes.

With distance interval tracking you create a tracking mode with a distance interval in meters of your choice.

Type

Unit

Unit Range

Distance Interval

Meters

1m ~ 2500m

Distance between location updates example code:

// Define a custom tracking method with desired distance interval, stop duration and accuracy
val trackingMode = RoamTrackingMode.Builder(<DISTANCE-FILTER-IN-METERS>, <STOP-INTERVAL-IN-SECONDS>)
            .setDesiredAccuracy(RoamTrackingMode.DesiredAccuracy.HIGH)
            .build()
// Start the tracking with the above created custom tracking method
Roam.startTracking(trackingMode, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })

Time Interval Tracking

With Time Interval Tracking you can create a tracking mode with the time interval (in seconds) of your choice.

Type

Unit

Unit Range

Time Interval

Seconds

10s ~ 10800s

Time between location updates example code:

// Define a custom tracking method with desired time interval and accuracy
val trackingMode = RoamTrackingMode.Builder(<TIME-INTERVAL-IN-SECONDS>)
            .setDesiredAccuracy(RoamTrackingMode.DesiredAccuracy.HIGH)
            .build()
// Start the tracking with the above created custom tracking method
Roam.startTracking(trackingMode, object:TrackingCallback(){
            override fun onSuccess(p0: String?) {
                //do something
            }

            override fun onError(p0: RoamError?) {
                //do something
            }
        })

You may see a delay if the user's device is in low power mode or has connectivity issues.

Stop Tracking

To stop tracking, use the method below.

Roam.stopTracking(object : TrackingCallback {
            override fun onSuccess(s: String) {
              //do something
            }
            override fun onError(roamError: RoamError) {
              //do something
            }
        })

Location Listeners

Listeners are needed to consume the location or event data from the SDK. To enable listeners, ensure the following:

  • To listen to location updates, create a class that extends RoamReceiver.

  • Register the receiver by adding a receiver element to the application element in your manifest.

Note: For self-tracking, you can only listen to only location, error, and offline trips status data since the locations are not being sent to our servers for processing events.

<application>
        ...
     <receiver android:name=".LocationReceiver"
                    android:enabled="true"
                    android:exported="false">
         <intent-filter>
         <action android:name="com.roam.android.RECEIVED"/>
         </intent-filter>
     </receiver>
         ...
</application>

Add the code to the receiver.

class LocationReceiver: RoamReceiver() {
    override fun onLocationUpdated(context: Context?, roamLocations: MutableList<RoamLocation>?) {
        super.onLocationUpdated(context, roamLocations)
        // receive own location updates here
        // do something with location data using location
            for (roamLocation in roamLocations!!){
                roamLocation.activity
                roamLocation.recordedAt
                roamLocation.timezoneOffset
                roamLocation.metadata
                roamLocation.batteryStatus
                roamLocation.networkStatus
                roamLocation.location.latitude
                roamLocation.location.longitude
                roamLocation.location.bearing
                roamLocation.location.altitude
                roamLocation.location.accuracy
                roamLocation.location.speed
                roamLocation.location.provider
                roamLocation.location.time
                roamLocation.location.verticalAccuracyMeters
            }
    }

    override fun onError(context: Context?, roamError: RoamError?) {
        super.onError(context, roamError)
        // receive error message here
         roamError?.code
         roamError?.message
    }
}

Batch Configuration

Batch configuration lets you control the number of location data updates being received in the location listener with the desired frequency and window.

Set Batch Configuration

As the name suggests, this method sets the configuration parameters.

  1. The NetworkState.BOTH indicates the state in which the updates are to be received. It can either be set to online, offline, or both.

  2. The batchCount indicates the size of the location batch.

  3. The batchWindow indicates the time interval for every consecutive update (frequency of updates).

By default, the batch configuration values for both batch count and window are set to 1 and 0 respectively.

Roam.setBatchReceiverConfig(
    NetworkState.BOTH,
    batchCount,
    batchWindow,
    object : RoamBatchReceiverCallback {
        override fun onSuccess(list: List<BatchReceiverConfig>) {
            list[i].networkState
            list[i].batchCount
            list[i].batchWindow
        }
        override fun onFailure(roamError: RoamError) {
            roamError.code
            roamError.message
        }
    })

Consider the following call,

Roam.setBatchConfig("NetworkState.Both", 5 , 60)

The batch count value is the number of location updates sent in a batch. In the above case, the value is set to 5. Ideally, the SDK sends 5 updates per batch and the batch window (in the above case, 60) specifies the number of seconds the SDK waits to receive five location updates.

If the SDK receives 5 location updates in less than 60 seconds, the updates are pushed to the listener. If not, it waits for 60 seconds and pushes the location updates regardless of the batch count value.

Success Callback - We receive a list of BatchReceiveConfig objects.

Example response:

[{"batchCount":5,"batchWindow":10,"networkState":"OFFLINE"}, {"batchCount":5,"batchWindow":10,"networkState":"ONLINE"}]

Error Callback: We receive a RoamError object in the error callback.

The available details to get from the RoamError object are: error.getMessage() and error.getCode()

Get Batch Configuration

The get receiver config method allows the user to get the current batch configuration for the location listener.

Roam.getBatchReceiverConfig(object : RoamBatchReceiverCallback {
    override fun onSuccess(list: List<BatchReceiverConfig>) {
        list[i].networkState
        list[i].batchCount
        list[i].batchWindow
    }
    override fun onFailure(roamError: RoamError) {
        roamError.code
        roamError.message
    }
})

The response for the above code is the same as that of the Set Receiver Config method.

Reset Batch Configuration

The Reset Batch Configuration method allows the user to reset the batch config for the location listener.

Roam.resetBatchReceiverConfig(object : RoamBatchReceiverCallback {
    override fun onSuccess(list: List<BatchReceiverConfig>) {
        list[i].networkState
        list[i].batchCount
        list[i].batchWindow
    }
    override fun onFailure(roamError: RoamError) {
        roamError.code
        roamError.message
    }
})

Last updated