LocationManager returns old cached "Wifi" location with current timestamp

Viewed 5959

I am trying to get the current location. For that I implement a LocationListener and register it for both the network and the GPS provider:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

I block then for 30 seconds and use the first location that gets passed into the listener's

onLocationChanged()

method with an accuracy of 100 meters or better.

Most of the time this works fine. If the phone is connected to some Wifi network, it takes just a second to get a correct location with an accuracy of about 50 meters. If there is no Wifi but GPS is enabled, it can of course take a while to get a location.

Sometimes however, when connected to a Wifi and getting the current location, some old (cached?) previous "Wifi" location is provided - it might be 15 minutes old and 15 kilometers away from the current location. The problem is, that

location.getTime()

returns the current time - so it is impossible to know that the location is old.

I guess I have to implement a more elaborate solution - I would just like to know why these old "Wifi" locations have a current timestamp instead one from the time when it was originally retrieved.

3 Answers

I have been facing the same issues until I made some changes to my code.

What happened is that I was attaching the same LocationListener when requesting for both GPS and Network location updates and I was getting "weird" issues including getting old WIFI location updates with current time.

Here's my old code:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);

Apparently that is a rather "unsafe" thing to do (sorry, Android newbie here) and so I changed it to:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, gpsLocationListener);

Of course I had to define 2 separate onLocationChanged block of codes to handle the 2 listeners.

Well, it did solve my problem. I tested this on Gingerbread (API Level: 8). Not sure if it works for you.

Related