Created
May 31, 2023 07:01
-
-
Save oussama-dz/28074a99502b371691fb23f135ad9167 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.
This file contains hidden or 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
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