Development/Android

Android GPS Turn On

Lonepine 2019. 2. 21. 11:06

Turn on GPS Programmatically in Android 4.4 or Higher


if (isGpsOff())
{
tryGpsOn()
}
private fun isGpsOff():Boolean {
return !(getSystemService(Context.LOCATION_SERVICE) as LocationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)
}
private fun tryGpsOn() {
val googleApiClient:GoogleApiClient = GoogleApiClient.Builder(applicationContext).addApi(LocationServices.API).build()
googleApiClient.connect()


val builder:LocationSettingsRequest.Builder = LocationSettingsRequest.Builder().addLocationRequest(LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
interval = 30 * 1000;
fastestInterval = 5 * 1000;
})
builder.setAlwaysShow(true) // this is the key ingredient

val result= LocationServices.SettingsApi .checkLocationSettings(googleApiClient, builder.build())
result.setResultCallback {
result: LocationSettingsResult ->

val status = result.status
val state = result .getLocationSettingsStates()

when(status.getStatusCode())
{
LocationSettingsStatusCodes.SUCCESS->{}
LocationSettingsStatusCodes.RESOLUTION_REQUIRED->{
try {
status.startResolutionForResult(this@RenewalPlaceActivity, 1000);
}
catch (e: IntentSender.SendIntentException)
{

}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE->{}
}
}

}



Reference Link : https://www.instructables.com/id/Turn-on-GPS-Programmatically-in-Android-44-or-High/