Last active
November 11, 2021 09:16
-
-
Save MostafaGad1911/7674ab4719e9ce05049e216aefe9f0d4 to your computer and use it in GitHub Desktop.
Current location Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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