Location sources:
- GPS
- ~5-10 m accuracy
- Timing precision in the order of 20 ns
- Requires special/general theories of relativity to be taken into effect
- Cell-ID (cell tower triangulation)
- Wi-Fi network
Android has three methods to obtain location:
- GPS
- Most accurate and most energy intensive
- Only works outdoors
- Network Location Provider: combines Cell-ID and Wi-Fi data
- Passive: piggybacks off other applications
Permissions:
<manifest>
// Foreground: one-off access to location
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
// If you want fine access, you must also request coarse
// Gives you accses to GPS location
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
// Background: requires permission on API level 29 and higher
<uses-permission
android:name="android.permission.ACCESS_BACKGROUND_LOCATION"
/>
</manifest>
Older approach was easy to get wrong: forgetting to disable it and leading to large battery drain:
- Use
LocationManagerto get access to system location servicesgetSystemService(Context.LOCATION_SERVICE)
- Implement
LocationListenersubclass: overrideonLocationChanged,onStatusChanged,onProviderEnabled,onProviderDisabledmethods
Newer approach uses Google Play Services and provides a higher-level API:
- Provides Fused Location Provider: combines multiple location sources in a unified interface
-
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) fusedLocationClient.lastLocation.addOnSuccessListener {location: Location? -> // Check to ensure accuracy hasn't dropped significantly (e.g. if phone switched from GPS to network) } - Can also request location requests using
LocationCallback:onLocationResult - Geofencing
- Set entrance and exit events
- Max. 100 geofences per app
- Requires fine location, background location permissions