Skip to content

Instantly share code, notes, and snippets.

Created July 26, 2016 12:06
Show Gist options
  • Save anonymous/891fe8f73751ac9f6e1a59bfbfcb58a0 to your computer and use it in GitHub Desktop.
Save anonymous/891fe8f73751ac9f6e1a59bfbfcb58a0 to your computer and use it in GitHub Desktop.
Android location tracking background service in Kotlin language. Referenced from: http://stackoverflow.com/a/28535885/1441324
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
class LocationTrackingService : Service() {
var locationManager: LocationManager? = null
override fun onBind(intent: Intent?) = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
override fun onCreate() {
if (locationManager == null)
locationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
try {
locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, INTERVAL, DISTANCE, locationListeners[1])
} catch (e: SecurityException) {
Log.e(TAG, "Fail to request location update", e)
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Network provider does not exist", e)
}
try {
locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, DISTANCE, locationListeners[0])
} catch (e: SecurityException) {
Log.e(TAG, "Fail to request location update", e)
} catch (e: IllegalArgumentException) {
Log.e(TAG, "GPS provider does not exist", e)
}
}
override fun onDestroy() {
super.onDestroy()
if (locationManager != null)
for (i in 0..locationListeners.size) {
try {
locationManager?.removeUpdates(locationListeners[i])
} catch (e: Exception) {
Log.w(TAG, "Failed to remove location listeners")
}
}
}
companion object {
val TAG = "LocationTrackingService"
val INTERVAL = 1000.toLong() // In milliseconds
val DISTANCE = 10.toFloat() // In meters
val locationListeners = arrayOf(
LTRLocationListener(LocationManager.GPS_PROVIDER),
LTRLocationListener(LocationManager.NETWORK_PROVIDER)
)
class LTRLocationListener(provider: String) : android.location.LocationListener {
val lastLocation = Location(provider)
override fun onLocationChanged(location: Location?) {
lastLocation.set(location)
// TODO: Do something here
}
override fun onProviderDisabled(provider: String?) {
}
override fun onProviderEnabled(provider: String?) {
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment