How can I get notified when Google Play Services can not get a location fix?

1.3k views Asked by At

I have an android application that needs to ascertain its current location (Using Google Play Services LocationClient) and then send that location back to a server. This needs to happen in the background at regular intervals e.g. Every 5 minutes

This code is working very well and it generally delivers the locations every 5 minutes within a few seconds tolerance. The problem occurs when android can not get a fix. Under these conditions I was expecting the callback to be run after 5 minutes with a NULL location object, however this does not happen. The Application merely continues to look for locations without ever calling the callback.

I call my LocationClient's requestLocationUpdates method with a locationRequest object created as follows

locationrequest = LocationRequest.create();
locationrequest.setInterval(5 * 60 * 1000);  
locationrequest.setFastestInterval(3 * 60 * 1000);
locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationrequest.setExpirationDuration(45 *1000);
locationclient.requestLocationUpdates(locationrequest, mPendingIntent);

I can not see a suitable way to have the LocationClient call me every 5 minutes, even when it is not able to get a location. I appreciate that I could have an alarm that goes off every 5 minutes and then sends the most recent location back to the server but I was hoping to handle the sending within the callback.

Has anyone else had to handle this situation, or have any idea how to address it?

1

There are 1 answers

3
Rarw On

I don't know what you're doing in the rest of the code but I think you just need to manage your LocationRequest and LocationClient in relation to the lifecycle methods of the Activity or Fragment you are calling them from.

The receiving location updates tutorial along with this post from the android developers blog are good examples.

Since your app must be connected to LocationClient to recieve updates if you switch these updates on and off during say onResume() or onCreate() and onStop() you effectivly only run the timer when you app is in the foreground. Then, as the developer blog post suggests, when your app is in the background you can switch over to a passive location listener that can still recieve updates but does not user the same timer based approach. When your app comes back to the foreground you can turn off the passive listener, reconnect to Google Play Services and start your 5 minute timer again.