【发布时间】:2013-02-17 16:58:41
【问题描述】:
我想在 android 中获取当前的确切位置坐标。如果手机连接到 Wifi 互联网连接,我可以获取位置,但在其他情况下,当我去其他地方并且没有可用的互联网连接时,它不会提供当前位置坐标。而是给出最后的位置坐标。
例如:
目前我在 A 市,通过 wifi 连接获取当前坐标并移动到 B 市,然后我无法获取当前坐标。取而代之的是,它给出了最后的位置坐标。
谁能建议我如何在没有互联网连接的情况下获取当前位置。
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from 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();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GetLocations.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
【问题讨论】:
-
安卓使用AGPS,你不能。
-
@Raghav Sood 没有办法解决我的问题??
-
AGPS 代表辅助 GPS。在此,GPS 模块由来自互联网的数据辅助。没有互联网 = 没有 AGPS
-
您的问题实际上是当 NETWORK AND GPS 提供商都被禁用时,您如何获取位置? (因为 GPS 在没有网络的情况下工作。)你不能。您可以使用最近的已知位置,但如果没有启用其中一个提供程序,您将无法获得新的位置更新。
-
另外,如果您使用 Criteria 并且只是遍历可用的提供程序并分配第一个满足您条件的提供程序,您的代码会简单得多。