Skip to content

Instantly share code, notes, and snippets.

@mars-amn
Created October 8, 2019 16:43
Show Gist options
  • Save mars-amn/1aa2bc4ee36a885e6b17b26a81f66a7b to your computer and use it in GitHub Desktop.
Save mars-amn/1aa2bc4ee36a885e6b17b26a81f66a7b to your computer and use it in GitHub Desktop.
private fun GeofencePickerClick() {
checkIfUserEnabledLocationNetwork() // don't call it unless you're sure that the user granted location permission
}
private fun checkIfUserEnabledLocationNetwork() {
val responseTask = getLocationNetworkTask()!!
responseTask.addOnSuccessListener { startMapActivity() }
.addOnFailureListener {
val apiException = it as ApiException
when (apiException.statusCode) {
CommonStatusCodes.RESOLUTION_REQUIRED -> {
try {
val exception = it as ResolvableApiException
exception.startResolutionForResult(
this,
NETWORK_LOCATION_REQUEST_CODE
)
} catch (e: IntentSender.SendIntentException) {
longToast(R.string.error_msg)
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> longToast(R.string.error_msg)
}
}
}
private fun getLocationNetworkTask(): Task<LocationSettingsResponse>? {
val locationRequest = LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
val settingsRequest = LocationSettingsRequest.Builder()
settingsRequest.addLocationRequest(locationRequest)
val client = LocationServices.getSettingsClient(this@AddEditNoteActivity)
return client.checkLocationSettings(settingsRequest.build())
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && data != null) {
when (requestCode) {
NETWORK_LOCATION_REQUEST_CODE -> {
val states = LocationSettingsStates.fromIntent(data)
if (states.isNetworkLocationPresent) {
startMapActivity() // here the Netwok location is available.
}
}
}
}
companion object {
private const val NETWORK_LOCATION_REQUEST_CODE = 33
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment