我想使用以下代码在我的 APP 中获取位置:
public Location getLocation() {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
try {
// Getting GPS and Network status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) return null;
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ((location != null && (location.getTime() + 60000 < System.currentTimeMillis())) ||
location == null){
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return location;
}
当我使用 Nexus 4 时,它可以正常工作并且位置具有价值。但是当我在 Galaxy S2 location = null 中执行相同的代码时。
在调用该函数之前,我已经检查了 GPS 和网络是否都已启用。
您将如何纠正此功能?
在调用这个函数之前,我称之为:
public void startLocation() {
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (Exception e) {
e.printStackTrace();
}
}