I am trying to create an app for my own use that enables/disables certain features like WiFi, GPS, etc; my question pertains to GPS. Note that my phone is not rooted and I would like to keep it that way.
I have successfully enabled GPS using the following code:
public void toggleGPS() {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
LocationRequest locationRequest = new LocationRequest();
if (isGPSEnabled()) {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(60 * 60 * 1000);
locationRequest.setFastestInterval(60 * 60 * 1000);
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
}
googleApiClient.connect();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
Status status = result.getStatus();
LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
}
}
});
}
So when GPS isn't on, this code prompts me to turn it on, as I want. However, it doesn't seem to shut off when I request Balanced Power and set the larger intervals and no other app is using GPS. I assumed that if my app no longer needs high accuracy, then GPS will automatically be switched off. Am I misunderstanding something? And is there any way to switch it off? I can sort of understand the security concerns for disallowing GPS to be ENABLED programmatically, but I don't understand why Android wouldn't allow it to be DISABLED.
Thanks in advance!