【发布时间】:2014-03-05 13:51:28
【问题描述】:
我目前有一项服务,这种服务很有效。它检查是否启用了 GPS,如果启用,它将获取 GPS 位置,并且我的地图可以缩放到该位置。它有getLastKnownLocation。问题是,getLastKnownLocation 可能在数英里之外(就像我昨天尝试的那样)。
它首先运行 GPS 检查,因为它已启用它不会运行网络检查位置。
有没有办法让它在启用 GPS 的情况下,但除了 getLastKnownLcation() 之外无法修复,默认为基于网络的位置?之后我会检查,如果网络未启用或 lastKnownLocation 太远,我可以检查 Wifi。
这是我的服务代码:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//Minimum distance for update
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 40; //40 seconds
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
Log.i("i", "Get location called");
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
this.canGetLocation = true;
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("GPS_LOCATION", "Location: "+location.toString());
if(location.toString().contains("0.000000")) {
Log.i("Called", "Called inside");
isNetworkEnabled = true;
isGPSEnabled = false;
getLocation();
}
}
}
}
}
else if (isNetworkEnabled) {
Log.d("Network", "Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("NETWORK_LOCATION", "Location: "+location.toString());
}
}
}
else if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled and GPS is off.
Log.d("NOT ENABLED", "Use WIFI");
}
return location;
}
昨天发生的事情是,我离家几英里远,连接了 wifi 并启用了 GPS,但发生的情况是,虽然我的位置通过 Wifi 更新,但地图上出现了蓝点。它不会放大它。由于 GPS 已启用(但无法修复),它沿着这条路线走并得到了LastKnownLocation(),它回到了我家。即使蓝点是正确的,它仍会一直缩放到我上次所在的位置。
有没有办法让它检查 GPS 但不使用LastKnownLocation?相反,它默认为网络检查,然后网络检查将不使用lastknownLocation,它将默认为Wifi。如果需要,Wifi 可以有 LastKnownLocation。实际上,我只想在 Wifi 阶段获得lastKnownLocation 作为最后的手段。
希望有人可以帮助我。我不认为从代码中删除lastKnownLocation 这么简单。
感谢您提供的任何帮助。
【问题讨论】:
标签: android networking geolocation gps location