Android: the best way to get instant location in one go
I've always had some difficulty finding a good way to instantly locate the device. What I want to do is once per use of the app (like when onCreate is called from an activity). I want to know the coordinates of the device at this exact moment and not ask them again. I think the best way is something like a static class with a function like:
coordinates getCoordinates();
Some tips / snippets to give?
source to share
I found what I was really looking for in the answer THIS .
I only added two controls; i check if:
- gps_loc.getTime () (or net_loc.getTime ()) is greater than System.currentTimeMillis () - 300000 (5 minutes ago). In the run () method of the GetLastLocation inner class;
- location.getAccuracy () <100. In onLocationChanged () method as LocalListeners (network and GPS).
Hope it helps!
source to share
Use LocationManager.getLastKnownLocation
or LocationManager.requestSingleUpdate
.
The former will be returned immediately, but may return null if the location is no longer available.
The second one returns your data on a callback, but wakes up whatever the provider needs and gets a good seat (if possible).
source to share