Android:快速获取GPS位置

use*_*779 4 gps android

我需要在我的应用程序中找到一个GPS位置,这个位置不需要准确(只有大约1km的精度),但我需要它非常!(1S-5S)

我注册了这个监听器:

mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Run Code Online (Sandbox Code Playgroud)

但是找到修复需要很长时间!有没有人知道一种方法,我可以更快地找到位置(我基本上只需要设备所在的当前城镇).谢谢!

Abh*_*nda 8

由于您不需要非常精细的粒度位置而且需要快速,因此您应该使用它getLastKnownLocation.像这样的东西:

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);
Run Code Online (Sandbox Code Playgroud)

编辑:Android开发博客在这里做了一个很好的帖子.来自博客的此片段会迭代所有位置提供程序以获取最后的已知位置.这似乎是你需要的

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Pre*_*rem 5

为此,您可以使用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);
    }
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此链接.

然后使用提供程序获取您的位置.

希望这会有所帮助......