Friday, February 10, 2012

How to get the last known GPS location in android?

First we are going to fetch a list of location providers with lm.getProviders(true) (likely ['network','gps']). Then we're going to loop over the array backwards: 
private double[] getGPS() {
 LocationManager lm = (LocationManager) getSystemService(
  Context.LOCATION_SERVICE);
 List<String> providers = lm.getProviders(true);

 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;
}

No comments:

Post a Comment