Skip to content

Instantly share code, notes, and snippets.

@ahmedMubarak2024
Last active July 27, 2022 10:20
Show Gist options
  • Save ahmedMubarak2024/f284cad273aed1ae860402bcfe5a9aa7 to your computer and use it in GitHub Desktop.
Save ahmedMubarak2024/f284cad273aed1ae860402bcfe5a9aa7 to your computer and use it in GitHub Desktop.
check on location services is turn on if not show native dialog to user that can enable the location service
class LocationActivity:AppCompatActivity() {
private val REQUEST_TURN_DEVICE_LOCATION_ON = 29
private val TAG = this::class.java.simpleName
private fun checkDeviceLocationSettings(resolve:Boolean = true, context:AppCompatActivity) {
val locationRequest = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val settingsClient = LocationServices.getSettingsClient(context)
val locationSettingsResponseTask =
settingsClient.checkLocationSettings(builder.build())
locationSettingsResponseTask.addOnFailureListener { exception ->
if (exception is ResolvableApiException && resolve){
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
exception.startResolutionForResult(context,
REQUEST_TURN_DEVICE_LOCATION_ON)
} catch (sendEx: IntentSender.SendIntentException) {
Log.d(TAG, "Error geting location settings resolution: " + sendEx.message)
}
} else {
Snackbar.make(
//View ,
R.string.location_required_error, Snackbar.LENGTH_INDEFINITE
).setAction(android.R.string.ok) {
checkDeviceLocationSettings(context=this)
}.show()
}
}
locationSettingsResponseTask.addOnCompleteListener {
if ( it.isSuccessful ) {
//location is turn on
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_TURN_DEVICE_LOCATION_ON) {
// We don't rely on the result code, but just check the location setting again
checkDeviceLocationSettings(false,this)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment