正如标题所说,我正在关注Android开发者网站上的代码并尝试获取当前位置的纬度和经度。我正在使用Android Studio和模拟器。当我使用getLatitude()和getLongitude()时,我不知道为什么我的代码传递null - 我以为我按照指定的方式遵循了代码。
谢谢!
(班级需要什么)HomePage.java:
public void onConnected(@Nullable Bundle bundle) {
if (location == null){
declareLocation();
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
SharedPreferences sharedPreferences = getSharedPreferences("example.com.musicapptest", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong("latitude", Double.doubleToLongBits(latitude));
editor.putLong("longitude", Double.doubleToLongBits(longitude));
}
private Location declareLocation(){
try{
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
catch (SecurityException e){
e.printStackTrace();
}
return location;
}
答案 0 :(得分:0)
许多因素可能导致这种情况。 ApiClient是否已连接?你做得对吗?如果这两个都是真的,那么位置是不可用的。
引用参考:
返回当前可用的最新位置。
如果某个位置不可用,这种情况很少发生,则会返回null。将返回尊重位置权限时可用的最佳准确度。
此方法提供了获取位置的简化方法。它特别适用于不需要精确定位且不希望为位置更新维护额外逻辑的应用程序。
您还可以使用getLocationAvailability().isLocationAvailable()
来确定是否返回null。如果此方法返回false,则需要使用requestLocationUpdates()
方法请求位置更新。
关于位置更新,您可以参考本指南:https://developer.android.com/training/location/index.html