我有一個服務在那種作品。它會檢查GPS是否啓用,是否會獲取GPS位置,並且我的地圖可以縮放到該位置。它有getLastKnownLocation
。問題是,getLastKnownLocation
可能在數英里之外(就像我昨天試過的那樣)。通過GPS獲取用戶位置然後網絡然後Wifi
首先運行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
那麼簡單。
感謝您提供的任何幫助。