Android: get GPS post quickly

I need to find a GPS location in my app, which doesn't have to be accurate (only about 1 km from accuracy), but I need it very quickly ! (1s-5s)

I register this listener:

mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);

      

But it takes too long to find a fix! Does anyone know of a method by which I can find the location faster (I basically need the current city the device is in). Thank!

+3


source to share


2 answers


To do this, you can define your criteria using criteria.

public void setCriteria() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
        provider = locationManager.getBestProvider(criteria, true);
    }

      

For more information see the link.



And then use a provider to retrieve your location.

Hope this helps ...

+5


source


Since you don't need a very fine-grained location and you need it quickly, you should use getLastKnownLocation

. Something like that:

LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);

      



Edit: The Android dev blog has a nice entry here . This blog snippet is repeated across all location providers to get the last known location. This looks like what you need

List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
  Location location = locationManager.getLastKnownLocation(provider);
  if (location != null) {
    float accuracy = location.getAccuracy();
    long time = location.getTime();

    if ((time > minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
    }
    else if (time < minTime && 
             bestAccuracy == Float.MAX_VALUE && time > bestTime){
      bestResult = location;
      bestTime = time;
    }
  }
}

      

+7


source







All Articles