Get the phone's last known location using LocationManager

4 votes · 7 comments

This is a fast code to get the last known location of the phone. If there is no exact gps-information it falls back to the network-based location info. This code is using LocationManager. [updated]

raw ·
copy
· download
private double[] getGPS() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = lm.getProviders(true); /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ Location l = null; for (int i=providers.size()-1; i>=0; i--) { l = lm.getLastKnownLocation(providers.get(i)); if (l != null) break; } double[] gps = new double[2]; if (l != null) { gps[0] = l.getLatitude(); gps[1] = l.getLongitude(); } return gps; }
Add a comment

7 Comments

An improvement to this would be:

// This fetches a list of available location providers List providers = lm.getProviders(true)

This should return an array like this, depending on what is available:

['network', 'gps']

The last one will always be the most accurate, so you can then do

/ Loop over the array backwards, and if you get an accurate location, then break out the loop/ for (int i=providers.length();i>=0;i--) { Location l = lm.getLastKnownLocation(providers[i]); if (l != null) break; }

Reply · April 7, 2009, 7:29 p.m.

Thanks for your comments!

I've checked the code again and updated it with your suggestions. Works perfect and quite flexible like this!

Reply · July 9, 2009, 11:02 p.m.

Excellent, just what I needed. Cheers Guys!

Reply · Sept. 11, 2009, 5:50 p.m.

Hi, shouldn't it be either what Tane Piper said that is:

for (int i=providers.length();i>=0;i--)

OR

for (int i=providers.length()-1;i>0;i--)

you seem to the minus 1 but u have i>=0

Reply · March 19, 2011, 12:19 a.m.

nvm, i was drunk

Reply · March 19, 2011, 12:25 a.m.

it work as it tells

Reply · Dec. 11, 2012, 9:41 a.m.

how do i use this????

Reply · April 23, 2013, 1:27 p.m.