So I found something that is not very clear for me about GoogleApiClient. GoogleApiClient has a function called onConnected which is run wh
call connect() method in onStart()method
@Override
protected void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
I had the same error, but my problem was different from iheanyl's answer:
I had declared the googleApiClient static. This prevented android from shutting down the service.
I had this issue when I accidentaly but googleApiClient.connect() in oncreate and onresume. Just removed it from oncreate.
Moving GoogleApiClient from onStartCommand to onCeate resolved my issue
I had this problem to and I solved it with declaring googleApiClient as static object
I think I found the root of the problem and it has nothing to do with the API. I have faced this issued every time I install the app. By the way just like the most popular comment I only have one googleApiClient upon pause and resume. What I noticed is that the permission request to get geolocation access pops up. As you know in your activity this is going to turn into a pause, and once the popup is gone it resumes your activity. Most likely your googleClient is also chained to those events to disconnect and connect. You can tell there is no connection once the permission is accepted and you are about to perform the googleApiClient task.
if(googleApiClient.isConnected()){
rxPermissions
.request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(granted -> {
if (granted) {
//here it could be client is already disconnected!!
_geolocateAddress(response);
} else {
// Oups permission denied
}
});
}
You can skip disconnecting and connecting as you set a flag which is true before permission and once the googleApiClient task is completed or granted
is false.
if(googleApiClient.isConnected()){
isRequestingPermission = true;
rxPermissions
.request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(granted -> {
if (granted && googleApiClient.isConnected()) {
//Once the task succeeds or fails set flag to false
//at _geolocateAddress
_geolocateAddress(response);
} else {
// Oups permission denied
isRequestingPermission = false;
}
});
}
We could also split doing permission alone, and if granted then make the task call. Ok, I am going to confess I am using a fragment, and I reinstalled the app even rotated the screen on permissions and once granted, the result showed up. I hope this helps other people.