How to get the coarse location using Wifi or GSM or GPS, whichever is available?

Sibbs Gambling picture Sibbs Gambling · Jul 16, 2013 · Viewed 26.7k times · Source

My app only needs a coarse location service when started up.

In detail, I need the app's rough location so as to provide the users with the shop info nearby.

The location does NOT need to be updated constantly. In addition, coarse localization will be sufficient in this case.

I wish the app to choose GSM, or wifi, or GPS automatically, whichever is available.

The location service should also be one-time to save phone energy.

How may I do that?

I have tried using GPS separately.

My problem is I don't know how to stop the constantly-refreshing-location feature of GPS. I don't know how to make the phone select one out of the three methods, either.

Some sample codes or ideas are greatly appreciated.

Answer

g00dy picture g00dy · Jul 16, 2013

Here's a certain point of view:

private void _getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) 
            getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}

This might however request a FINE_LOCATION access. So:

Another way is to use this which uses the LocationManager.

The quickest possible way is to use the Last Known location with this, I used it and it's quite fast:

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