Skip to content

aws-geospatial/amazon-location-mobile-tracking-sdk-android

Amazon Location Service Mobile Tracking SDK for Android

These utilities help you when making Amazon Location Service API calls from your Android applications. This library uses the AWS SDK to call tracking APIs.

Installation

This tracking SDK works with the overall AWS SDK and the Amazon Location Authentication SDK. All SDKs are published to Maven Central. Check the latest version of auth SDK and tracking SDK on Maven Central.

Add the following lines to the dependencies section of your build.gradle file in Android Studio:

implementation("software.amazon.location:tracking:1.0.0")
implementation("software.amazon.location:auth:1.1.0")
implementation("aws.sdk.kotlin:location:1.3.65")

Functions

These are the functions available in this SDK:

ClassFunctionDescription
LocationTracker constructor(context: Context,locationCredentialsProvider: LocationCredentialsProvider,trackerName: String)
or
constructor(context: Context,locationCredentialsProvider: LocationCredentialsProvider,clientConfig: LocationTrackerConfig)
This is an initializer function to create a LocationTracker object. It requires LocationCredentialsProvide and trackerName and an optional LocationTrackingConfig. If config is not provided it will be initialized with default values
LocationTrackerstart(locationTrackingCallback: LocationTrackingCallback)Starts the process of accessing the user's location and sending it to the AWS tracker
LocationTrackerisTrackingInForeground()Checks if location tracking is currently in progress.
LocationTrackerstop()Stops the process of tracking the user's location
LocationTrackerstartBackground(mode: BackgroundTrackingMode, serviceCallback: ServiceCallback)Starts the process of accessing the user's location and sending it to the AWS tracker while the application is in the background. BackgroundTrackingMode has the following options:
- ACTIVE_TRACKING: This option actively tracking user's location updates
- BATTERY_SAVER_TRACKING: This option tracking user's location updates every 15 minutes
LocationTrackerstopBackgroundService()Stops the process of accessing the user's location and sending it to the AWS tracker while the application is in the background.
LocationTrackergetTrackerDeviceLocation() Retrieves the device location from AWS location services.
LocationTrackergetDeviceLocation(locationTrackingCallback: LocationTrackingCallback?) Retrieves the current device location from the fused location provider client and uploads it to AWS location tracker.
LocationTrackeruploadLocationUpdates(locationTrackingCallback: LocationTrackingCallback?) Uploads the device location to AWS location services after filtering based on the configured location filters.
LocationTrackerenableFilter(filter: LocationFilter) Enables particular location filter.
LocationTrackercheckFilterIsExistsAndUpdateValue(filter: LocationFilter) Checks filter exists in Location tracker config if not add one.
LocationTrackerdisableFilter(filter: LocationFilter) Disable particular location filter.
LocationTrackerConfig LocationTrackerConfig( // Required var trackerName: String, // Optional var locationFilters: MutableList = mutableListOf( TimeLocationFilter(), DistanceLocationFilter(), ), var logLevel: TrackingSdkLogLevel = TrackingSdkLogLevel.DEBUG, var accuracy: Int = Priority.PRIORITY_HIGH_ACCURACY, var latency: Long = 1000, var frequency: Long = 1500, var waitForAccurateLocation: Boolean = false, var minUpdateIntervalMillis: Long = 1000, var persistentNotificationConfig: NotificationConfig = NotificationConfig() ) This initializes the LocationTrackerConfig with user-defined parameter values. If a parameter value is not provided, it will be set to a default value
LocationFiltershouldUpload(currentLocation: LocationEntry, previousLocation: LocationEntry?): BooleanThe LocationFilter is a protocol that users can implement for their custom filter implementation. A user would need to implement `shouldUpload` function to compare previous and current location and return if the current location should be uploaded

Prerequisite for background location

To utilize background location, include the following permission and service entries within your AndroidManifest.xml file.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<application>
    <service
        android:name="software.amazon.location.tracking.providers.BackgroundLocationService"
        android:enabled="true"
        android:exported="true"
        android:foregroundServiceType="location" />
</application>

Usage

Import the following classes in your code:

import software.amazon.location.tracking.LocationTracker
import software.amazon.location.tracking.config.LocationTrackerConfig
import software.amazon.location.tracking.util.TrackingSdkLogLevel

import aws.sdk.kotlin.services.location.LocationClient

import software.amazon.location.auth.AuthHelper
import software.amazon.location.auth.LocationCredentialsProvider

Create an AuthHelper as we need LocationCredentialsProvider for creating LocationTracker:

// Create an authentication helper using credentials from Cognito
private fun exampleCognitoLogin() {
    val authHelper = AuthHelper(applicationContext)
    val locationCredentialsProvider : LocationCredentialsProvider = authHelper.authenticateWithCognitoIdentityPool("My-Cognito-Identity-Pool-Id")
}

OR

// Create a credentail provider using custom credential provider with AuthHelper
private fun exampleCustomCredentialLogin() {
    var authHelper = AuthHelper(applicationContext)
    var locationCredentialsProvider : LocationCredentialsProvider = authHelper.authenticateWithCredentialsProvider("MY-AWS-REGION", "MY-CUSTOM-CREDENTIAL-PROVIDER")
}

Use the LocationCredentialsProvider and LocationTrackerConfig to create a LocationTracker:

val config = LocationTrackerConfig(
    trackerName = "MY-TRACKER-NAME",
    logLevel = TrackingSdkLogLevel.DEBUG,
    accuracy = Priority.PRIORITY_HIGH_ACCURACY,
    latency = 1000,
    frequency = 5000,
    waitForAccurateLocation = false,
    minUpdateIntervalMillis = 5000,
)
locationTracker = LocationTracker(
    applicationContext,
    locationCredentialsProvider,
    config,
)

You can use the LocationTracker to get the device's location and upload it:

locationTracker?.getDeviceLocation(object :LocationTrackingCallback{
      override fun onLocationReceived(location: LocationEntry) {
      }

      override fun onUploadStarted(entries: List<LocationEntry>) {
      }

      override fun onUploaded(entries: List<LocationEntry>) {
      }

      override fun onUploadSkipped(entries: LocationEntry) {
      }

      override fun onLocationAvailabilityChanged(locationAvailable: Boolean) {
      }
})

You can use the LocationTracker to start and stop tracking in the foreground. Here is an example:

// Starting location tracking
locationTracker?.start(object :LocationTrackingCallback{
      override fun onLocationReceived(location: LocationEntry) {
      }

      override fun onUploadStarted(entries: List<LocationEntry>) {
      }

      override fun onUploaded(entries: List<LocationEntry>) {
      }

      override fun onUploadSkipped(entries: LocationEntry) {
      }

      override fun onLocationAvailabilityChanged(locationAvailable: Boolean) {
      }
})

// Stopping location tracking
locationTracker?.stop()

You can also use the LocationTracker to start and stop tracking in the background. Here is an example:

// Starting location tracking
locationTracker?.startBackground(
    BackgroundTrackingMode.ACTIVE_TRACKING,
    object : ServiceCallback {
        override fun serviceStopped() {
            if (selectedTrackingMode == BackgroundTrackingMode.ACTIVE_TRACKING) {
                isLocationTrackingBackgroundActive = false
            } else {
                isLocationTrackingBatteryOptimizeActive = false
            }
        }
    },
)

// Stopping location tracking
locationTracker?.stopBackgroundService()

How to use filters

The Amazon Location Service Mobile Tracking SDK includes three location filters:

  • TimeLocationFilter: Filters location updates based on a defined time interval.
  • DistanceLocationFilter: Filters location updates based on a specified distance threshold.
  • AccuracyLocationFilter: Filters location updates by comparing the distance moved since the last update with the current location's accuracy.

Filters can be added when the tracker is initially configured. They can also be adjusted during runtime. Here is an example of using a filter in the initial configuration:

val config = LocationTrackerConfig(
    trackerName = "MY-TRACKER-NAME",
    logLevel = TrackingSdkLogLevel.DEBUG,
    accuracy = Priority.PRIORITY_HIGH_ACCURACY,
    latency = 1000,
    frequency = 5000,
    waitForAccurateLocation = false,
    minUpdateIntervalMillis = 5000,
    locationFilters = mutableListOf(TimeLocationFilter(), DistanceLocationFilter(), AccuracyLocationFilter())
)
locationTracker = LocationTracker(
    applicationContext,
    locationCredentialsProvider,
    config,
)

Custom filters can be added when the tracker is initially configured. Here is an example of using a custom filter in the initial configuration:

// Custom filter added to the location filters list. This filter checks if the current location's time corresponds to Monday.
val config = LocationTrackerConfig(
    trackerName = "MY-TRACKER-NAME",
    logLevel = TrackingSdkLogLevel.DEBUG,
    accuracy = Priority.PRIORITY_HIGH_ACCURACY,
    latency = 1000,
    frequency = 5000,
    waitForAccurateLocation = false,
    minUpdateIntervalMillis = 5000,
    persistentNotificationConfig = NotificationConfig(
        notificationImageId = R.drawable.ic_drive,
    ),
    locationFilters = mutableListOf(object : LocationFilter{
            override fun shouldUpload(
                currentLocation: LocationEntry,
                previousLocation: LocationEntry?
            ): Boolean {
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = currentLocation.time

                val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)

                return dayOfWeek == Calendar.MONDAY
            }
        }
    )
)
locationTracker = LocationTracker(
    applicationContext,
    locationCredentialsProvider,
    config,
)

Filters can be enabled or disabled at runtime with LocationTracker. Here is an example:

// To enable the filter
locationTracker?.enableFilter(TimeLocationFilter())

// To disable the filter
locationTracker?.disableFilter(TimeLocationFilter())

Security

See CONTRIBUTING for more information.

Getting Help

The best way to interact with our team is through GitHub. You can open an issue and choose from one of our templates for bug reports, feature requests or guidance. If you have a support plan with AWS Support, you can also create a new support case.

Contributing

We welcome community contributions and pull requests. See CONTRIBUTING.md for information on how to set up a development environment and submit code.

License

The Amazon Location Service Mobile Tracking SDK for Android is distributed under the Apache License, Version 2.0, see LICENSE.txt and NOTICE.txt for more information.

About

No description, website, or topics provided.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages