Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Get a GPS postion quickly

Tags:

android

gps

I need to find a GPS location within my app which does not need to be accurate (just around 1km of accuracy) but I need it very fast! (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 that takes too long to find a fix! Does anyone know a method with which I can find the location faster (I basically just need the current town the device is in). Thanks!

like image 653
user934779 Avatar asked Mar 18 '12 17:03

user934779


2 Answers

Since you do not need very fine grained location and you need it fast, you should use getLastKnownLocation. Something like this:

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: Android dev blog has a nice post here on doing this. This snippet from the blog iterates over all location providers to get the last known location. This seems to be 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;
    }
  }
}
like image 135
Abhishek Chanda Avatar answered Sep 22 '22 11:09

Abhishek Chanda


For that 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 refer this link.

And then use the provider to fetch your location.

Hope this will help...

like image 40
Prem Avatar answered Sep 21 '22 11:09

Prem