Skip to main content

Usage Examples for Android apps

1. Documentation​

You can find the complete Javadoc documentation for the TelematicsSDK here.

All classes used in these examples belong to the com.sentilant.telematicssdk package, except the exceptions, which belong to com.sentilant.telematicssdk.exceptions.


2. Usage​

Here you have some usage examples of the TelematicsSDK.

A typical integration follows this flow:

  1. Initialize the SDK with the user's tokens (2.1).
  2. Register the vehicle (2.3).
  3. Make sure all permissions are granted (2.5).
  4. Start the telematics service (2.6).

2.1 Initialization​

Initialize the SDK in your main activity or application class, typically in the onCreate method.

The SDK is initialized with the access token and refresh token of the authenticated user, together with the base URL of the telematics platform provided by Sentilant.

OptionRequiredDescription
baseUrlYesBase URL of the telematics platform (e.g. https://telematics.example.com).
tokenYesAccess token of the user.
tokenExpiresNoExpiry of the access token, as an ISO 8601 timestamp (e.g. 2026-11-03T12:43:29.562522Z).
refreshTokenNoRefresh token of the user. Supplying it enables automatic token renewal.
refreshTokenExpiresNoExpiry of the refresh token, as an ISO 8601 timestamp.

When a refresh token is supplied, the SDK renews the access token on its own, before it expires or when the server rejects it. Your application does not need to provide new tokens while the session remains valid. Without a refresh token, the SDK uses the access token as-is until it stops working.

build() throws an IllegalArgumentException if the base URL or the token is empty, or if an expiry is not a readable ISO 8601 timestamp.

After a successful initialization, the SDK retrieves the authenticated user automatically. No additional login call is required.

import com.sentilant.telematicssdk.TelematicsCallback;
import com.sentilant.telematicssdk.TelematicsSDK;
import com.sentilant.telematicssdk.TelematicsTokenInitOptions;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TelematicsSDK sdk = TelematicsSDK.getInstance(getApplicationContext());

TelematicsTokenInitOptions options;
try {
options = new TelematicsTokenInitOptions.Builder("TELEMATICS_BASE_URL", "ACCESS_TOKEN")
.tokenExpires("ACCESS_TOKEN_EXPIRES")
.refreshToken("REFRESH_TOKEN")
.refreshTokenExpires("REFRESH_TOKEN_EXPIRES")
.build();
} catch (IllegalArgumentException e) {
// Invalid options (empty base URL or token, or unreadable expiry)
return;
}

sdk.initSDK(options, new TelematicsCallback() {
@Override
public void onSuccess() {
// Initialization succeeded
}

@Override
public void onError(TelematicsSDKException e) {
// Handle initialization error
}
});
}
}

2.2 Session lifecycle​

Authentication invalidated​

Register a listener to be notified when the SDK can no longer authenticate. Several listeners can be registered; all of them are notified on the main thread. Remove the listener when it is no longer needed (for example, in onStop).

ReasonSession destroyedDescription
REFRESH_TOKEN_EXPIREDYesThe refresh token expired.
REFRESH_TOKEN_REJECTEDYesThe server rejected the refresh token.
ACCESS_TOKEN_REJECTEDYesThe server rejected the access token of a session without a refresh token.
ACCOUNT_INACTIVENoThe user account is inactive. The credentials remain valid.
ACCESS_DENIEDNoThe server refused access. The credentials remain valid.

reason.invalidatesSession() returns true when the session was destroyed. In that case the SDK has already stopped telemetry and removed the user and vehicle. To restore the session:

  1. obtain new tokens and call initSDK again;
  2. set the vehicle again (setVehicle);
  3. call startTelematicsService again. Telemetry does not restart by itself.

Data collected before the invalidation is kept on the device and is uploaded automatically once the session is restored.

import com.sentilant.telematicssdk.AuthInvalidationReason;
import com.sentilant.telematicssdk.TelematicsAuthenticationInvalidatedListener;

TelematicsAuthenticationInvalidatedListener authListener = reason -> {
if (reason.invalidatesSession()) {
// Session destroyed: obtain new tokens, call initSDK, setVehicle and startTelematicsService
} else {
// Access refused (e.g. inactive account): the session is kept
}
};

sdk.addAuthenticationInvalidatedListener(authListener);

// When no longer needed
sdk.removeAuthenticationInvalidatedListener(authListener);

Session state​

getSessionState() returns what the SDK knows about its session, without making any request. It can be called from any thread.

StatusDescription
NOT_AUTHENTICATEDNo credentials: the SDK was never initialized, or the user logged out.
VERIFIEDThe server accepted the current access token (at getLastVerifiedAt()).
UNVERIFIEDThere are credentials, but the server has not confirmed them yet.
DENIEDThe server refused access (e.g. inactive account). New credentials would not help.
INVALIDThe server rejected the session. New tokens must be provided through initSDK.

The returned TelematicsSessionState also exposes:

  • getInvalidationReason(): the reason for the INVALID or DENIED status, or null.
  • isAutoRenewing(): true if the SDK holds a refresh token and renews the access token on its own.
  • getRecoverableUntil(): until when the session can be kept alive without new tokens (ISO 8601), or null if unknown.
  • getLastVerifiedAt(): when the server last accepted the access token (ISO 8601), or null.

The status reflects the last answer from the server, not a live check.

import com.sentilant.telematicssdk.TelematicsSessionState;

TelematicsSessionState state = sdk.getSessionState();

if (state.getStatus() == TelematicsSessionState.Status.INVALID) {
// Obtain new tokens and call initSDK again
}

Current user​

Retrieve the identifier and the name of the authenticated user using getCurrentUserInfo:

import com.sentilant.telematicssdk.TelematicsUserCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;

sdk.getCurrentUserInfo(new TelematicsUserCallback() {
@Override
public void onTelematicsUserFetched(int userId, String userName) {
// Current user fetched successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error fetching current user
}
});

Use getCurrentUserInfo(TelematicsUserDetailsCallback) to receive the full TelematicsUserDetails object instead.

Logout​

logout() ends the session of the current user. It:

  1. stops telemetry, if the telematics service is running;
  2. tries to send the telemetry data still stored on the device to the server;
  3. ends the session, removing the credentials, the user and the vehicle from the SDK.

Data that could not be sent before the session ended (for example, without network) is kept on the device and is sent after the next successful initSDK.

After logout, the session state is NOT_AUTHENTICATED. To use the SDK again, call initSDK with the tokens of the new session.

sdk.logout();

2.3 Vehicle Management​

Set the user vehicle using the setVehicle method. The vehicle type, add reason and fuel type are identifier codes returned by getVehicleTypes, getAddVehicleReasons and getFuelTypes. Each of these methods returns, asynchronously, a map where the key is the name and the value is the identifier code.

import com.sentilant.telematicssdk.FuelTypesCallback;
import com.sentilant.telematicssdk.TelematicsCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;
import java.util.Map;

sdk.getFuelTypes(new FuelTypesCallback() {
@Override
public void onFuelTypesFetched(Map<String, Integer> fuelTypes) {
// e.g. {"Diesel": 1, "Gasoline": 2, ...}
}

@Override
public void onError(Exception e) {
// Handle error fetching fuel types
}
});

// getVehicleTypes(VehicleTypesCallback) and getAddVehicleReasons(AddVehicleReasonsCallback) work the same way

int vehicleType = 1;
int addReason = 1;
int fuelType = 1;

sdk.setVehicle("plate123", "internalPlate", vehicleType, addReason, fuelType, new TelematicsCallback() {
@Override
public void onSuccess() {
// Vehicle set successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error setting vehicle
}
});

If the vehicle already exists, it can be set by its license plate only. The vehicle details are returned in the callback, or an error if no vehicle with that plate exists:

import com.sentilant.telematicssdk.TelematicsVehicleDetails;
import com.sentilant.telematicssdk.TelematicsVehicleDetailsCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;

sdk.setVehicle("plate123", new TelematicsVehicleDetailsCallback() {
@Override
public void onTelematicsVehicleInfoFetched(TelematicsVehicleDetails vehicleInfo) {
// Vehicle set successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Vehicle not found or error setting vehicle
}
});

Other vehicle methods:

  • getCurrentVehicleInfo(TelematicsVehicleDetailsCallback): returns the details of the current vehicle, or an error if no vehicle is set.
  • clearVehicle(): removes the current vehicle from the SDK.

2.4 Report vehicle kms​

Report the vehicle's current kilometers using the reportKilometers method:

import com.sentilant.telematicssdk.TelematicsCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;

sdk.reportKilometers(1200, "Routine check", new TelematicsCallback() {
@Override
public void onSuccess() {
// Kilometers reported successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error reporting kilometers
}
});

Other kilometer methods:

  • correctKilometers(kilometers, observations, correctionCount, callback): corrects the odometer reading, applying the value to the given number of past records.
  • getEstimatedMileage(): returns the estimated current mileage in kilometers, or -1 if it cannot be estimated.

2.5 Permission Handling​

Check the required permissions using the getRequiredPermissions and checkPermissions methods, and the battery optimization state using isBatteryOptimizationDeactivated.

  • getRequiredPermissions() returns the Android permissions required by the SDK on the current device (e.g. android.permission.ACCESS_FINE_LOCATION). The list depends on the Android version.
  • checkPermissions() returns the required permissions that are not granted. An empty list means all permissions are granted.
  • isBatteryOptimizationDeactivated() returns true if battery optimization is disabled for the application.

Telemetry only starts when all required permissions are granted and battery optimization is disabled. See Permissions Setup.

import java.util.List;

String[] requiredPermissions = sdk.getRequiredPermissions();

List<String> missingPermissions = sdk.checkPermissions();
if (missingPermissions.isEmpty()) {
// All permissions are granted
} else {
// Request missing permissions
}

if (!sdk.isBatteryOptimizationDeactivated()) {
// Ask the user to disable battery optimization for the app
}

2.6 Telematics Service​

Start and stop the telematics service as needed. Before starting, the SDK validates, in order, that the session is valid, that a user and a vehicle are set, that all permissions are granted and that battery optimization is disabled. If any of these checks fails, the service is not started and onError is called.

TelematicsServiceOptions is optional (it can be null) and allows sending additional information with the start or stop: setReason, setObservations, setServiceCode, setVehicleKms, setRealVolume and setExtraData.

import com.sentilant.telematicssdk.TelematicsCallback;
import com.sentilant.telematicssdk.TelematicsServiceOptions;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;
import java.util.HashMap;
import java.util.Map;

Map<String, String> extraData = new HashMap<>();
extraData.put("key", "value");

TelematicsServiceOptions options = new TelematicsServiceOptions()
.setReason("Start of shift")
.setVehicleKms(1200)
.setExtraData(extraData);

// Start the service
sdk.startTelematicsService(options, new TelematicsCallback() {
@Override
public void onSuccess() {
// Telematics service successfully started
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error starting telematics service
}
});

// Check if the service is running
boolean isRunning = sdk.isTelematicsServiceRunning();

// Stop the service
sdk.stopTelematicsService(options, new TelematicsCallback() {
@Override
public void onSuccess() {
// Telematics service successfully stopped
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error stopping telematics service
}
});

stopTelematicsService(TelematicsCallback) stops the service without options. setServiceCode(serviceCode, callback) changes the service code used by the telematics service.

2.7 Attention Detection​

While the telematics service is running, the SDK can detect on the device, using a machine learning model, when the user is handling the phone while driving. Each detection produces an attention event.

  • Attention detection is enabled by default and runs only while the telematics service is running.
  • Use setAttentionDetectionEnabled(false) to disable it. The choice is persisted and applies immediately if the service is running. While disabled, telemetry is collected exactly as without this feature.
  • Attention events are stored on the device and uploaded to the platform automatically, in the same way as telemetry data.
  • Each event covers a 10 second window. A new window starts every 5 seconds, so a continuous distraction may produce several events.

Register a listener to receive the events in your application. Several listeners can be registered; all of them are notified on the main thread. Events detected while no listener is registered are not delivered later.

import com.sentilant.telematicssdk.TelematicsAttentionEvent;
import com.sentilant.telematicssdk.TelematicsAttentionEventListener;

TelematicsAttentionEventListener attentionListener = event -> {
// event.getType() -> TelematicsAttentionEventType.PHONE_DISTRACTION
// event.getStartTimestampMs() / event.getEndTimestampMs() -> window, epoch milliseconds
// event.getConfidence() -> 0..1
};

sdk.addAttentionEventListener(attentionListener);

// When no longer needed
sdk.removeAttentionEventListener(attentionListener);

// Enable or disable attention detection
sdk.setAttentionDetectionEnabled(true);
boolean enabled = sdk.isAttentionDetectionEnabled();

TelematicsAttentionEvent fields:

FieldTypeDescription
getId()StringUnique identifier of the event (UUID).
getType()TelematicsAttentionEventTypeEvent type. Currently PHONE_DISTRACTION.
getStartTimestampMs() / getEndTimestampMs()longStart and end of the window, epoch milliseconds.
getConfidence()doubleDetection confidence, from 0 to 1.
getAverageSpeedMps()DoubleMean GPS speed during the window in m/s, or null.
getLatitude() / getLongitude()DoublePosition of the first valid GPS fix in the window, or null.
getHorizontalAccuracyM()DoubleHorizontal accuracy of that fix in meters, or null.
getLocationTimestampMs()LongTime of that fix, epoch milliseconds, or null.
getDetectorVersion()StringIdentifier of the detector that produced the event.

The location fields are either all set or all null. toMap() returns the event as a map with the same keys used on iOS and React Native.

2.8 Trips​

Retrieve a list of trips within an optional date range.

On Android, the SDK expects startDate and endDate as ISO 8601 strings with timezone, in the format:

YYYY-MM-DDTHH:mm:ssZ (example: 2026-01-01T00:00:00Z)

import com.sentilant.telematicssdk.TelematicsTripResume;
import com.sentilant.telematicssdk.TelematicsTripsCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;
import java.util.List;

// Example ISO 8601 with timezone (UTC)
String startDate = "2026-01-01T00:00:00Z";
String endDate = "2026-01-31T23:59:59Z";

// You can pass null to remove one of the filters:
// String startDate = null;
// String endDate = null;

sdk.getTrips(startDate, endDate, new TelematicsTripsCallback() {
@Override
public void onTelematicsTripsFetched(List<TelematicsTripResume> trips) {
// Trips list fetched successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error fetching trips list
}
});

To retrieve the details of a single trip, use getTrip(id, includeSamples, TelematicsTripCallback). The trip details are delivered in onTelematicsTripFetched(TelematicsTripDetail trip). Set includeSamples to true to include the trip samples in the response.

2.9 Metrics Summary​

Retrieve a summary of user metrics within an optional date range.

On Android, startDate and endDate must be ISO 8601 strings with timezone, using:

YYYY-MM-DDTHH:mm:ssZ (example: 2026-01-01T00:00:00Z)

import com.sentilant.telematicssdk.TelematicsMetricsSummary;
import com.sentilant.telematicssdk.TelematicsMetricsSummaryCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;

// Example ISO 8601 with timezone (UTC)
String startDate = "2026-01-01T00:00:00Z";
String endDate = "2026-01-31T23:59:59Z";

// You can pass null to remove one of the filters:
// String startDate = null;
// String endDate = null;

sdk.getMetricsSummary(startDate, endDate, new TelematicsMetricsSummaryCallback() {
@Override
public void onTelematicsMetricsSummaryFetched(TelematicsMetricsSummary summary) {
// Metrics summary fetched successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error fetching metrics summary
}
});

Other metrics methods:

  • getActivityMetricsSummary(startTimestamp, endTimestamp, TelematicsActivityMetricsSummaryCallback): activity metrics summary for an optional date range (ISO 8601).
  • getLastTelematicsPeriodMetricsSummary(TelematicsMetricsSummaryCallback): metrics summary of the last telematics period.
  • getLastTelematicsDayMetricsSummary(TelematicsMetricsSummaryCallback): metrics summary of the last telematics day.

2.10 Telematics Periods​

Retrieve the telematics periods within an optional date range (ISO 8601). isProcessed filters by processed state and can be null.

  • getTelematicsPeriods(from, to, isProcessed, page, TelematicsPeriodsCallback): one page of periods (TelematicsPeriodsPage). page can be null to use the default page. An overload without page is also available.
  • getAllTelematicsPeriods(from, to, isProcessed, TelematicsPeriodsListCallback): the full list of periods.
  • getTelematicsPeriod(id, TelematicsPeriodCallback): the details of a single period.
import com.sentilant.telematicssdk.TelematicsPeriod;
import com.sentilant.telematicssdk.TelematicsPeriodsListCallback;
import com.sentilant.telematicssdk.exceptions.TelematicsSDKException;
import java.util.List;

sdk.getAllTelematicsPeriods("2026-01-01T00:00:00Z", "2026-01-31T23:59:59Z", null, new TelematicsPeriodsListCallback() {
@Override
public void onTelematicsPeriodsFetched(List<TelematicsPeriod> periods) {
// Telematics periods fetched successfully
}

@Override
public void onError(TelematicsSDKException e) {
// Handle error fetching telematics periods
}
});

2.11 Manual Events​

Manual events allow the user to mark, during a trip, the moment a specific driving event happened (for example, a hard braking or a distraction).

The SDK records the event type with the current time and the latest location collected by the SDK, and sends it to the server. The event is therefore meant to be inserted while a trip is being recorded.

Later, when analysing the trip, the manual events can be compared with the events detected automatically by the SDK.

Example: If a manual distraction event is marked at minute 10 of a trip, you can check whether a distraction event was also detected at that minute, and use this comparison to validate the trip and assess the reliability of the event detection.

Register a manual event using insertManualEvent. The available types are defined in TelematicsManualEventType: ABRUPT_ACCELERATION_HIGH_SPEED, ABRUPT_ACCELERATION_LOW_SPEED, HARD_BRAKING_HIGH_SPEED, HARD_BRAKING_LOW_SPEED, HARD_CORNERING, SPEEDING, DISTRACTION, WALKING, DRIVING, STOPPED, TRIP_START and TRIP_END.

import com.sentilant.telematicssdk.TelematicsManualEventType;

sdk.insertManualEvent(TelematicsManualEventType.HARD_BRAKING_HIGH_SPEED);

2.12 Errors​

Errors are delivered as TelematicsSDKException (package com.sentilant.telematicssdk.exceptions) or one of its subclasses:

ExceptionWhen
TelematicsSDKNotAuthenticatedExceptionThe SDK has no valid session.
TelematicsSDKSessionExpiredExceptionThe session expired (subclass of TelematicsSDKNotAuthenticatedException).
TelematicsSDKMissingUserExceptionNo user is set.
TelematicsSDKMissingVehicleExceptionNo vehicle is set.
TelematicsSDKMissingPermissionExceptionOne or more required permissions are not granted.
TelematicsSDKBatteryOptimizationExceptionBattery optimization is enabled for the application.