我正在尝试使用this教程后的LocationManager
检索位置。
我正在运行Marshmallow的Android设备上运行代码,并且我已经检查了权限并在授予权限后在代码下运行。
这是我的代码:
public Location getLocation() {
try {
locationManager = (LocationManager) 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
Log.d("noProviderEnabled", "called");
} 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);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
currentLatDouble = location.getLatitude();
currentLngDouble = 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);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
即使已启用WiFi,isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
正在返回false
并且Log.d("noProviderEnabled", "called");
正在打印出来。
GPS
然后运行上述代码时, 更新:只有isNetworkEnabled
返回true
和isGPSEnabled
仍然已退回false
。
这里有什么问题?即使启用了WiFi,为什么我无法使用LocationManager.NETWORK_PROVIDER
检索位置?
P.S。:这在Android L及以下版本上运行得非常好。