Skip to main content

Accessing device location

The LocationService is a set of utilities that help you access and react to the device location.

LocationService

If your application needs location information, LocationService can help you get this information while also simplifying the process and being flexible enough to use different services.

Location Provider
See location provider if you only need to access the current location puck position on the map.

The LocationService supports the following location providers:

  • Google's Fused Location Providers
  • Android GPS and Network Providers

You can access the LocationService and get a DeviceLocationProvider using:


val locationService : LocationService = LocationServiceFactory.getOrCreate()
var locationProvider: DeviceLocationProvider? = null

val request = LocationProviderRequest.Builder()
.interval(IntervalSettings.Builder().interval(0L).minimumInterval(0L).maximumInterval(0L).build())
.displacement(0F)
.accuracy(AccuracyLevel.HIGHEST)
.build();

val result = locationService.getDeviceLocationProvider(request)
if (result.isValue) {
locationProvider = result.value!!
} else {
Log.error("Failed to get device location provider")
}

This will get the most suitable DeviceLocationProvider that is available.

Requesting location updates

To receive location updates, create a LocationObserver and override the onLocationUpdateReceived function to handle the locations:


val locationObserver = object: LocationObserver {
override fun onLocationUpdateReceived(locations: MutableList<Location>) {
Log.e(TAG, "Location update received: " + locations)
}
}
locationProvider.addLocationObserver(locationObserver)

To stop receiving updates, remove your observer:


locationProvider.removeLocationObserver(locationObserver);

You can register for location updates via a PendingIntent on the DeviceLocationProvider:


locationProvider.requestLocationUpdates(myPendingIntent)
locationProvider.removeLocationUpdates(myPendingIntent)

You can also register a LocationObserver with a Looper object, the message queue will then be used to implement the callback mechanism:


addLocationObserver(observer: LocationObserver, looper: Looper)

The location provider automatically starts and stops collecting locations based on the amount of subscribers: once the first subscriber is registered, the service starts, and when the last observer is unregistered, the service stops.

If you want to get the last known location, you can do so via the asynchronous LocationProivder.getLastLocation function. The function returns a Cancelable object which allows cancelling the request if needed:


val lastLocationCancelable = locationProvider.getLastLocation { result ->
result?.let { doSomething(it) }
}

To cancel the request, call


lastLocationCancelable.cancel()
Was this page helpful?