Radar.trackOnce() call will return RadarStatus.SUCCESS with a location and a user that you can find in the Radar dashboard.
This page documents Android SDK 4.3.0. The source and the releases are on GitHub.
Most examples are in Kotlin. Every method is also callable from Java through a callback interface, and the core setup examples show both.
Install SDK
We recommend adding the SDK to your project with Gradle in Android Studio.Gradle (recommended)
The SDK is distributed using Maven Central. Add the SDK to thedependencies section of your app’s build.gradle file:
Add manually
You can also add the SDK to your project manually. Download the current release and unzip the package. The package contains anaar file. Add the aar file to your app module as a local dependency.
Dependencies
If you haven’t already configured your project for Google Play Services, follow the Google services setup instructions.
If another dependency that depends on
play-services-location causes version conflicts, you can exclude the transitive dependency and include play-services-location at the project level instead. Use 21.0.1 or later.
As an alternative to Google Play Services, the SDK optionally supports Huawei Mobile Services.
Optional dependencies
Some SDK features need a library that the SDK doesn’t add for you. Add the library only if you use the feature:
From Android SDK 4.3.0, the SDK includes R8 rules for the Huawei and Firebase libraries. You don’t need to add
-dontwarn rules to your proguard-rules.pro file when you minify your app. If you added these rules for an earlier SDK version, you can remove them:
Initialize SDK
When your app starts, initialize the SDK with your publishable key from the Settings page. CallRadar.initialize() on the main thread in Application.onCreate(), before you call any other Radar method.
Use your test publishable key (prj_test_pk_...) for the Test environment and your live publishable key (prj_live_pk_...) for the Live environment.
Radar.initialize() has three forms:
Application class:
Application class in the manifest with android:name on the <application> element.
Radar.isInitialized() returns true after initialization. Radar.sdkVersion() returns the SDK version string.
Initialization options
RadarInitializeOptions is a Kotlin data class. From Java, use RadarInitializeOptions.Builder.
networkTimeout and ipChangeDebounceInterval are persisted when you set them. If you pass null, the SDK uses the previously saved value, or the default.
For example, to pass options when you initialize the SDK:
receiver, provider, and fraud as arguments: Radar.initialize(context, publishableKey, receiver, provider, fraud). Its parameters have Kotlin default values and no Java overloads, so from Java use RadarInitializeOptions.Builder.
Network timeout
To override the default network timeout, setnetworkTimeout on RadarInitializeOptions as a Kotlin Duration. The extended timeout used for longer-running requests is automatically set to 2.5 times this value. Values are clamped to the range 1 to 300 seconds. For example, to set a 30-second timeout:
Request permissions
Radar respects standard Android location permissions. The SDK doesn’t show permission prompts. Your app requests runtime permissions.Manifest requirements
The SDK manifest merges these permissions into your app automatically:ACCESS_FINE_LOCATIONandACCESS_COARSE_LOCATIONINTERNETandACCESS_NETWORK_STATERECEIVE_BOOT_COMPLETEDFOREGROUND_SERVICE
RadarLocationReceiver, RadarBootReceiver (which restores tracking after a reboot or an app update), and the RadarJobScheduler job service. You don’t declare these yourself.
Add these to your app manifest yourself, only when you use the feature:
A manifest for background tracking and a foreground service:
Runtime permissions
Request foreground location permission first. On Android 11 (API level 30) and later, request
ACCESS_BACKGROUND_LOCATION in a separate request after the user grants foreground permission. The system sends the user to a settings screen to choose Allow all the time.
For when to ask, how to explain each prompt, and how to handle denial and approximate location, see Location permissions.
If a permission prompt doesn’t appear, check that the permission is in your merged manifest and that the device hasn’t already recorded a choice for your app in Settings.
Foreground tracking
Once the user has granted foreground permission, you can track the user’s location in the foreground.
To track the user’s location in the foreground, call:
To check your integration, build and run the app, then find your user on the Users page. To generate an event, first create a geofence around your location on the Geofences page. If the user doesn’t appear, check
status in the callback.
Get location
To get the device’s current location without sending it to Radar, call:onComplete receives (status: RadarStatus, location: Location?, stopped: Boolean). For example:
Background tracking for geofencing
Once you have initialized the SDK and the user has authorized background permission, you can start tracking the user’s location in the background. The SDK supports custom tracking options as well as three presets. See Tracking options. For geofencing, useRadarTrackingOptions.RESPONSIVE. This preset detects whether the device is stopped or moving. When moving, it tells the SDK to send location updates to the server about every 2.5 minutes. When stopped, it tells the SDK to shut down to save battery. Once stopped, the device needs to move more than 100 meters to wake up and start moving again.
With background permission, background tracking works even if the app has been backgrounded or terminated by the system, because Android location services wake up the app to deliver location updates, and the SDK uses JobScheduler to schedule network requests.
Android can delay location updates significantly because of Doze and App Standby and background location limits, or if the device has connectivity issues, low battery, or Wi-Fi turned off. In practice, location updates may be sent to the server every 5 to 10 minutes while moving, faster if the screen is on or if other apps are requesting location, and slower otherwise. These restrictions apply to all apps that use location services.
The tracking methods are:
Radar.getTrackingOptions() returns the options in effect. If you set remote tracking options in the dashboard, they override the options you pass to startTracking, and Radar.isUsingRemoteTrackingOptions() returns true.
To test, go for a walk or a drive. If you don’t see location updates or events, check two things: once stopped, the device needs to move more than 100 meters to wake up, and the app needs background location permission in the device settings. Find your user on the Users page and events on the Events page.
Foreground services and Google Play policy
Geofencing doesn’t require a foreground service. The SDK registers nearby geofences with the Android Geofence API, and Android wakes up the app to deliver geofence transitions. TheRESPONSIVE and EFFICIENT presets never start a foreground service.
Google Play’s updated location permissions policy no longer accepts geofencing as a use case for foreground services. Only enable a foreground service, with the CONTINUOUS preset or foregroundServiceEnabled, for use cases that Google Play still allows, such as trips, navigation, or user-initiated location sharing. You must declare foreground service usage in the Play Console.
Starting in Android SDK 4.0.0, the SDK manifest doesn’t declare RadarForegroundService. To use the CONTINUOUS preset or foregroundServiceEnabled, declare the service and the FOREGROUND_SERVICE_LOCATION permission in your app manifest:
RadarForegroundService. If your app never uses the foreground service, remove it from your merged manifest:
Background tracking for trips
For trips, useRadarTrackingOptions.CONTINUOUS. This preset tells the SDK to send location updates to the server every 30 seconds, regardless of whether the device is moving.
To avoid background location limits, the continuous preset starts a foreground service with a notification while tracking. While the foreground service notification is shown, only foreground permission is required for tracking. To adjust the foreground service notification copy and behavior, see Android foreground service options. In Android SDK 4.0.0 and later, you must declare RadarForegroundService in your app manifest. If you publish on Google Play, declare foreground service usage in the Play Console.
To start or update tracking for the duration of a trip, pass tracking options to Radar.startTrip():
Mock tracking for testing
You can simulate a sequence of location updates without moving the device.
For example, to simulate a sequence of 10 location updates every 3 seconds by car from an origin to a destination, call:
Location metadata
The SDK can send motion activity, speed, heading, and pressure with location updates. Turn on theuseMotion or usePressure tracking option, in code or with remote tracking options.
To collect motion activity, add the activity recognition permissions to your manifest:
user.activityType, one of UNKNOWN, STATIONARY, FOOT, RUN, BIKE, or CAR.
Listening for events with a receiver
To listen for events, location updates, and errors client-side, create a class that extendsRadarReceiver. Then pass an instance of your receiver when you initialize the SDK in Application.onCreate(), or call Radar.setReceiver().
RadarReceiver is an abstract class. You must implement all five methods:
For example, to set a receiver when you initialize the SDK:
Receiver lifecycle
- Create the receiver once and set it before tracking begins.
- Set the receiver in
Application.onCreate(), not in an activity. When Android starts your app process in the background to deliver a location update or geofence transition,Application.onCreate()runs and no activity is created. Radar.setReceiver()may be called beforeRadar.initialize(). The SDK keeps the receiver and uses it when it initializes. Passnullto clear the receiver.- Every callback receives a
Context. Use it instead of holding a reference to an activity.
RadarLocationSource is one of FOREGROUND_LOCATION, BACKGROUND_LOCATION, MANUAL_LOCATION, GEOFENCE_ENTER, GEOFENCE_DWELL, GEOFENCE_EXIT, MOCK_LOCATION, BEACON_ENTER, BEACON_EXIT, or UNKNOWN.
To listen for events server-side instead, add a webhook or enable an integration.
Manual tracking
If you manage location services yourself, you can update the user’s location manually. Pass aLocation instance with a valid latitude, longitude, and accuracy to:
Identify user
The SDK automatically collectsinstallId (a GUID generated on fresh install) and deviceId (Android ID).
For example, to identify a user:
userId set until the next user logs in. Clearing userId creates another user record.
Verified location
Radar.trackVerified() tracks the user’s location with device integrity information and returns a signed RadarVerifiedLocationToken that your backend validates. The verified location and risk methods require the Radar fraud plugin (io.radar:sdk-fraud) in addition to io.radar:sdk. Without a compatible plugin, they return RadarStatus.ERROR_PLUGIN.
Before you call these methods, install and configure the plugin. See Fraud plugin setup. For the end-to-end workflow, including backend token validation, see the Geo-compliance overview.
RadarTrackVerifiedCallback.onComplete receives (status: RadarStatus, token: RadarVerifiedLocationToken?). RadarRevealRiskCallback.onComplete receives (status: RadarStatus, token: RadarRevealRiskToken?).
For example, to run a location check at login:
RadarVerifiedLocationToken properties:
RadarVerifiedReceiver is an abstract class:
Debug logging
By default, only critical errors are logged to the console. To enable debug logging, call:RadarLogLevel is one of NONE, ERROR, WARNING, INFO, or DEBUG. A log level set in remote configuration overrides the level you set in code. To receive log messages in your app, implement onLog on your RadarReceiver.
The Android SDK observes activity lifecycle callbacks and logs app lifecycle events automatically, without the additional setup required on iOS. Radar.logResigningActive() and Radar.logBackgrounding() are public for wrapper SDKs. You don’t need to call them in a native app.
App lifecycle event logging must be enabled for your project. Contact your Radar account team.
Other APIs
The Android SDK also exposes APIs for beacons, trips, context, geocoding, search, distance, conversions, and user tags. Each method takes a callback interface, listed with the method. In Kotlin, you can pass a lambda with the same parameters instead. Check that the status isRadarStatus.SUCCESS before you use the other values.
Beacons
To range and monitor beacons, you must request Bluetooth permissions. On Android 12 (API level 31) and later, the SDK requires theBLUETOOTH_SCAN runtime permission and ACCESS_FINE_LOCATION. On earlier versions, it requires BLUETOOTH, BLUETOOTH_ADMIN, and ACCESS_FINE_LOCATION.
Add the Bluetooth permissions to your manifest:
RadarStatus.ERROR_BLUETOOTH.
To monitor beacons in the background, update your tracking options:
Radar.trackVerified(beacons = true), you can call Radar.startRangingBeacons() to range beacons continuously in the foreground, so that location checks don’t wait for a new ranging window.
Radar.startRangingBeacons() after initialize() and after location and Bluetooth permissions are granted, ideally when the user enters a flow that calls trackVerified(beacons = true). Call Radar.stopRangingBeacons() when you no longer need beacons. Ranging pauses automatically when the app enters the background and resumes when it returns to the foreground. Until ranging has run for 5 seconds, trackVerified(beacons = true) ranges beacons as usual. These methods require Android 8.0 (API level 26) or later.
Trips
For the workflow, see Track pickups, deliveries, and workers.RadarTripCallback.onComplete receives (status: RadarStatus, trip: RadarTrip?, events: Array<RadarEvent>?). RadarTripLegCallback.onComplete receives (status: RadarStatus, trip: RadarTrip?, leg: RadarTripLeg?, events: Array<RadarEvent>?).
RadarTripOptions properties:
Create a
RadarTripLeg with one of RadarTripLeg.forGeofence(tag, externalId), RadarTripLeg.forGeofenceId(geofenceId), RadarTripLeg.forAddress(address), or RadarTripLeg.forCoordinates(latitude, longitude).
For example, to start a trip with two legs and then complete the current leg:
Geocoding
With the forward geocoding API, geocode an address, converting address to coordinates:layers are optional layer filters. countries are optional two-letter country code filters. onComplete receives (status: RadarStatus, addresses: Array<RadarAddress>?). For example:
location gets the device’s current location first. For example:
RadarIpGeocodeCallback.onComplete receives (status: RadarStatus, address: RadarAddress?, proxy: Boolean, throwable: Throwable?). throwable is the underlying error, if any, so that you can forward it to an error reporting tool.
Search
With the autocomplete API, autocomplete partial addresses and place names, sorted by relevance. Create oneRadarAutocompleteSession per search field. When the user selects a result, call session.select. If your project has address enrichment enabled, selecting also returns the enriched address. RadarAutocompleteSession requires Android SDK 4.3.0 or later.
For example, to autocomplete a query and select the first result:
RadarAutocompleteSelectCallback.onComplete receives (status: RadarStatus, address: RadarAutocompleteEnrichedAddress?).
To autocomplete without a session, call Radar.autocomplete(query, near, layers, limit, country, mailable, callback) with the same parameters.
With the geofence search API, search for geofences near a location, sorted by distance:
onComplete receives (status: RadarStatus, location: Location?, geofences: Array<RadarGeofence>?). For example:
onComplete receives (status: RadarStatus, location: Location?, places: Array<RadarPlace>?). For example:
city, stateCode, postalCode, and countryCode. unit is optional; in Java, pass null to leave it out. If a required field is empty, the SDK returns RadarStatus.ERROR_BAD_REQUEST without sending a request.
RadarAddressVerificationStatus is one of VERIFIED, PARTIALLY_VERIFIED, AMBIGUOUS, UNVERIFIED, or NONE.
To validate an address from autocomplete or geocoding, pass its street and number (or its addressLabel) and the other fields to one of these methods. These methods are available in Android SDK 4.3.0 and later. In earlier versions, use validateAddress(address), which is deprecated. Addresses from autocomplete and geocoding have a street, a number, and an address label. Versions before 4.3.0 send all three, and the API rejects the request with RadarStatus.ERROR_BAD_REQUEST. On those versions, validate a new RadarAddress built without addressLabel.
Distance
With the distance API, calculate the travel distance and duration from an origin to a destination:origin uses the device’s current location. modes is a set of FOOT, BIKE, CAR, TRUCK, and MOTORBIKE. units is IMPERIAL or METRIC. onComplete receives (status: RadarStatus, routes: RadarRoutes?). RadarRoutes has geodesic and one optional RadarRoute per mode. For example:
Matrix
With the matrix API, calculate the travel distance and duration between multiple origins and destinations for up to 25 routes:RadarMatrixCallback.onComplete receives (status: RadarStatus, matrix: RadarRouteMatrix?). For example, to get the route between the first origin and the first destination:
Conversions
With the conversions API, log a conversion, such as a purchase or signup, to analyze alongside your app’s location activity:onComplete receives (status: RadarStatus, event: RadarEvent?). For example:
Verify events
After a user check-in or another form of verification, you can accept or reject an event. Radar uses event verifications to improve the accuracy and confidence level of future events.User tags
Set tags on the user so that you can target campaigns at users with the corresponding tags. Added in 3.22.0.
For example:
In-app messages
To customize how Radar in-app messages are handled, implementRadarInAppMessageReceiver and pass it in RadarInitializeOptions.inAppMessageReceiver or to Radar.setInAppMessageReceiver(). Every method of the interface has a default implementation: onNewInAppMessage(inAppMessage) shows the message with Radar.showInAppMessage(), and onInAppMessageDismissed(inAppMessage) and onInAppMessageButtonClicked(inAppMessage) do nothing. Override createInAppMessageView to supply your own view.
Notifications
WithRadar.setNotificationOptions(), set the icon and the background color of foreground service and event notifications. Pass a RadarNotificationOptions:
For example:
opened_app conversions with a Radar notification that the user tapped to open the app. The SDK does this from its activity lifecycle callbacks. Radar.logOpenedAppConversion(intent: Intent) is public for cases where you need to pass the launching intent yourself.
Huawei
By default, the SDK depends on Google Play Services Location. However, you can use Huawei Mobile Services Location Kit instead. If you haven’t already configured your project for Huawei Mobile Services, follow the HMS Core integration instructions. Then add the dependency to your app’sbuild.gradle file:
HUAWEI when you initialize the SDK:
Models
The SDK returns these model classes from theio.radar.sdk.model package. Models have a toJson() method for serialization.
For field definitions, see the API reference for users, events, and trips.