Skip to content

Instantly share code, notes, and snippets.

@sdzshn3
Last active December 19, 2020 10:51
Show Gist options
  • Select an option

  • Save sdzshn3/bfaf0a3f552d20e64383b9e50d902d82 to your computer and use it in GitHub Desktop.

Select an option

Save sdzshn3/bfaf0a3f552d20e64383b9e50d902d82 to your computer and use it in GitHub Desktop.
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
@SuppressLint("MissingPermission")
class MyLocation(
context: Context
) {
private val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private var onLocationChanged: ((Location) -> Unit)? = null
private val locationListenerGps: LocationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
onLocationChanged?.invoke(location)
}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
}
fun attachObserver(onLocationChanged: (Location) -> Unit) {
this.onLocationChanged = onLocationChanged
}
fun stopListening() {
locationManager.removeUpdates(locationListenerGps)
}
fun startListening() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, locationListenerGps)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment