我在我的应用程序中使用以下代码(来自教程等),以从 GPS(或者如果 GPS 未打开,则网络)获得最佳位置修复,然后将其显示在文本字段中。
crit = new Criteria();
context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(context);
crit.setAccuracy(Criteria.ACCURACY_FINE);
crit.setPowerRequirement(Criteria.POWER_LOW);
crit.setAltitudeRequired(false);
crit.setBearingRequired(false);
crit.setSpeedRequired(false);
crit.setCostAllowed(false);
try {
bestProvider = locationManager.getBestProvider(crit, true);
loc = locationManager.getLastKnownLocation(bestProvider);
locationManager.requestLocationUpdates(bestProvider, 0, 0,
new GeoUpdateHandler());
} catch (java.lang.RuntimeException run) {
Toast.makeText(getBaseContext(),
"Waiting for location fix...", Toast.LENGTH_SHORT).show();
}
我的问题是在不同地点之间移动。我开始在诺福克使用我的应用程序并确定位置。第二天,我在康沃尔(相距 100 英里),当我打开我的应用程序(此时它应该已被 Android 关闭/销毁)时,它仍然向我显示诺福克的位置。我发现如果我退出我的应用程序并重新启动它,它就会选择新的位置。我可以轻松做到这一点,但我的用户发现它真的很痛苦。
我的假设是,如果 GPS/网络可用,那么我启动应用程序,从最后一个已知位置创建 LOC,然后 locationManager 立即更新(应该立即更新 LOC?)使用:
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
loc = location;
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
显然这个更新没有发生。
谁能告诉我我的代码是否愚蠢,或者提供更好的方法来确保我始终处理当前位置?谢谢。抱歉,如果这个问题得到解答,很难在所有关于位置和 requestLocationUpdates 标签的帖子中找到。