Skip to content

Instantly share code, notes, and snippets.

@virendersran01
Forked from oussama-dz/LocationService.kt
Created July 23, 2023 14:40
Show Gist options
  • Save virendersran01/ad0235ba1d7ae201ce0364d293182b5f to your computer and use it in GitHub Desktop.
Save virendersran01/ad0235ba1d7ae201ce0364d293182b5f to your computer and use it in GitHub Desktop.
A Location service class that get the current user location, and handle any exceptions that maybe thrown.
class LocationService {
@SuppressLint("MissingPermission")
suspend fun getCurrentLocation(context: Context): Location {
if (!context.hasPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
throw throw LocationServiceException.MissingPermissionException()
}
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
val isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
if (!isGpsEnabled) {
throw LocationServiceException.LocationDisabledException()
}
if (!isNetworkEnabled) {
throw LocationServiceException.NoInternetException()
}
val locationProvider = LocationServices.getFusedLocationProviderClient(context)
val request = CurrentLocationRequest.Builder()
.setPriority(Priority.PRIORITY_HIGH_ACCURACY)
.build()
try {
val location = locationProvider.getCurrentLocation(request, null).await()
return location
} catch (e: Exception) {
throw LocationServiceException.UnknownException(e)
}
}
fun Context.hasPermissions(vararg permissions: String) =
permissions.all {
ActivityCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
}
sealed class LocationServiceException : Exception() {
class MissingPermissionException : LocationServiceException()
class LocationDisabledException : LocationServiceException()
class NoInternetException : LocationServiceException()
class UnknownException(val exception: Exception) : LocationServiceException()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment