Search code examples
androidandroid-location

Android Location Clarification


I am working on an on demand location providing solution but I find that the documentation are too confusing for me to find the most efficient solution.

Here's what I understood so far:

LocationManager.getLastKnownLocation() is basically a piggybacking method. If no other app has location enabled, your app will not return a location.

LocationManager.requestLocationUpdates(), I understand that this basically sets up a listener for location updates. The actual method that's called is "OnLocationChanged()" of the listener. So technically you can put your location display code in the "onLocationChanged"...

If that's the case... How do I actually get the updated location? I don't want to be updated EVERYTIME the location changed. I want the location on demand, not whenever it updates. How would I implement that?

===

My current guess is that... Once you setup the listener, whenever you call "getLastKnownLocation", it will be an updated one created by your listener. Is that true? Is that how it works?


Solution

  • If you turn off the location on the phone, and then turn it on, the last know location will return null.

    Now the actual method to start getting new location is the method

    requestLocationUpdates()
    

    This will update the

    getLastKnownLocation() 
    

    and while requestLocationUpdates() is being called, the

    onLocationChanged(Location location)
    

    will be called to invoke things that you need to do with the location object.

    So inside this method you manage the new location/ location changes.