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]
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;
}
10 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; }
Thanks for your comments!
I've checked the code again and updated it with your suggestions. Works perfect and quite flexible like this!
Excellent, just what I needed. Cheers Guys!
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
nvm, i was drunk
it work as it tells
how do i use this????
Copy and paste that code into your MainActivity, then use it.
double[] MyLoc = new double[2]; MyLoc = getGPS();
MyLoc[0] is now the lat, [1] is the long.
Or create a class with a constructor that sets the context, make this as a function in that class, then call this function as above after instantiating the class.
public class GetLocationNetGPS {
}
Hello, I seem to be a bit new to this. Could you list the steps more in detail? Thanks
i cant understand how to use this and where to use this?????????plzz help