Android: 如何检查位置是当前位置还是最后已知位置
Android: how to check the location is current location or last known location
在我的应用程序中,我从网络获取位置,如果网络不可用,我的代码 returns 最后一个位置,在这两种情况下,我都想知道该位置是当前位置还是最后一个已知位置。有人可以告诉我如何提前知道 this.Thanks
public Location getLocation() {
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
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();
}
}
}
else{ }
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
您需要使用 SharedPrefences
来实现
在共享中存储当前位置(纬度和经度最多约小数点后 5 位)preferences.Compare新位置与共享preferences.If中的位置相同,则新位置是您的最后一个已知位置,如果不是新位置是新位置,请将其再次保存在您的共享首选项中。
在我的应用程序中,我从网络获取位置,如果网络不可用,我的代码 returns 最后一个位置,在这两种情况下,我都想知道该位置是当前位置还是最后一个已知位置。有人可以告诉我如何提前知道 this.Thanks
public Location getLocation() {
try {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
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();
}
}
}
else{ }
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
您需要使用 SharedPrefences
来实现在共享中存储当前位置(纬度和经度最多约小数点后 5 位)preferences.Compare新位置与共享preferences.If中的位置相同,则新位置是您的最后一个已知位置,如果不是新位置是新位置,请将其再次保存在您的共享首选项中。