This example will show how track location position on Android. First we need to define the permission on manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Now we have to check if the permission is granted or otherwise let the user grant it.
val dangPermToRequest: List<String> = checkMissingPermissions()
if (dangPermToRequest.isNotEmpty()) {
requestPermissions(dangPermToRequest)
return
}
To use the location service, we need to get the location manager through getSystemService
locationManager = this.getSystemService(LOCATION_SERVICE) as LocationManager
Now we define the location listener and register it through our location manager.
private val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
...
}
}
private fun registerToLocationListener() {
...
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 9000, 0f, locationListener
)
}
If you use an Emulator, you have to define a location or better a route.
- Go to Emulator settings
- Open Location -> Routes
- Search for a location
- Press Route and add a destination
- Now press Play Route