Manish Kumar Sharma
Manish Kumar Sharma

Reputation: 13432

getLastKnownLocation() vs requestLocationUpdates()

I am surprised and would like to beg your pardon but couldn't find a clear answer to the fundamental difference between the two. So, here is my requirement:

I would like to capture user's location in interval of every 5 minutes. For scheduling in general I am using JobScheduler and am doing all the work in the background. So, I am using a job scheduled every 5 minutes to accomplish the above.

How do I accomplish it?

I have been researching and seems like there could be a better option to get a fix - use a PendingIntent to get location updates using requestLocationUpdates().

So, here is the issue:

It is documented that if I getLastKnownLocation() returns my current location and then I turn off my device and drive 30 miles and turn it back on(with GPS on of course), getLastKnownLocation() would return me the 30 miles older location.

But, I am confused as to the location returned by requestLocationUpdates(). Would it return the new location?

Upvotes: 1

Views: 898

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93569

getLastKnownLocation will return a location only if location is already on. It will return immediately. 99% of the time it will return null. It will not turn on location hardware or software. It can be used as an optimization, but should never be relied upon. Unless you're sure about what you're doing, you should forget this function exists.

requestLocationUpdates will return nothing immediately, and return a location on a callback. It will never return null. It will turn location hardware and software on, and send you updates when location changes. It may never call the callback if for some reason it can't get a location fix (airplane mode, in a tunnel and can't reach sattelites for gps, etc). It should be used whenever you need to keep getting location updates.

requestSingleUpdate is just like requestLocationUpdates, except it will only call the callback once, then turn off location tracking again. It should be used when you just want location right now, and don't care about updates.

Upvotes: 6

Related Questions