Skip to content

Instantly share code, notes, and snippets.

@MostafaGad1911
Last active November 11, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaGad1911/7674ab4719e9ce05049e216aefe9f0d4 to your computer and use it in GitHub Desktop.
Save MostafaGad1911/7674ab4719e9ce05049e216aefe9f0d4 to your computer and use it in GitHub Desktop.
Current location Observer
import android.annotation.SuppressLint
import android.app.Activity
import android.location.Location
import android.os.Looper
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
private val currentLocation: MutableLiveData<Location> by lazy { MutableLiveData<Location>() }
@SuppressLint("MissingPermission")
fun LifecycleOwner.startLocationUpdates(activity:Activity): LiveData<Location> {
if(activity.GpsEnabled()){
//To avoid multi observables from HomeActivity.
currentLocation.removeObservers(this)
LocationServices.getFusedLocationProviderClient(activity)
.requestLocationUpdates(getLocationRequest(),
object : LocationCallback() {
@SuppressLint("MissingPermission")
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
val location: Location? = p0?.lastLocation
if (location != null) {
if (currentLocation.value != null &&
currentLocation.value!!.distanceTo(location) < 10)
return
currentLocation.postValue(location)
}
}
},
Looper.getMainLooper())
}else{
Toast.makeText(this, "Enable your gps to continue", Toast.LENGTH_SHORT).show()
activity.GpsNotEnapled()
}
return currentLocation
}
private fun getLocationRequest(): LocationRequest = LocationRequest
.create().apply {
interval = 6000
fastestInterval = 4000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
fun Context.GpsEnabled(): Boolean {
val locationManager: LocationManager? = getSystemService(
LOCATION_SERVICE
) as LocationManager?
return locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER)!!
}
fun Context.GpsNotEnapled(){
val callGPSSettingIntent = Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS
)
startActivity(callGPSSettingIntent)
Toast.makeText(this, "Enable your gps to continue", Toast.LENGTH_SHORT).show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment