Last active
May 15, 2019 07:43
-
-
Save Hamadakram/f6579627da02fe3781cef302f4fcac06 to your computer and use it in GitHub Desktop.
Check if location service is enabled
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
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