Skip to content

Instantly share code, notes, and snippets.

@Hamadakram
Last active May 15, 2019 07:43
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 Hamadakram/f6579627da02fe3781cef302f4fcac06 to your computer and use it in GitHub Desktop.
Save Hamadakram/f6579627da02fe3781cef302f4fcac06 to your computer and use it in GitHub Desktop.
Check if location service is enabled
private fun checkLocationServices(context: Context) {
val googleApiClient = GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build()
googleApiClient.connect()
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 10000
locationRequest.fastestInterval = (10000 / 2).toLong()
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
builder.setAlwaysShow(true)
val task = LocationServices.getSettingsClient(context).checkLocationSettings(builder.build())
task.addOnCompleteListener {
try {
it.getResult(ApiException::class.java)
// Location service enabled
} catch (exception: ApiException) {
when (exception.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> { // Location Service not enabled
try {
val resolvable: ResolvableApiException = exception as ResolvableApiException
resolvable.startResolutionForResult(activity, REQUEST_LOCATION_SERVICE)
} catch (e: IntentSender.SendIntentException) {
Log.i("Location", "PendingIntent unable to execute request.")
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
Log.i("Location", "Location settings are inadequate, and cannot be fixed here. Dialog not created.")
}
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_LOCATION_SERVICE -> when (resultCode) {
Activity.RESULT_OK -> requestLocationPermission()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment