Android通过位置管理器获取经度和纬度

我正在尝试使用位置管理器获取用户位置,但该位置始终返回null。 我也要求用户打开gps。

这是我的代码:

int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION); if(permisioncheck == 0){ lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE); List providers = lm.getProviders(true); Location bestLocation = null; for (String provider : providers) { Location location = lm.getLastKnownLocation(provider); if (location == null) { continue; } if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { // Found best last known location: %s", l); bestLocation = location; } } if(bestLocation == null){ System.out.println("is NULL!"); } }else{ ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } 

我希望有人能帮助我找到错误,谢谢。

“错误”是您假设getLastKnownLocation()将返回一个Location 。 通常,它将返回null 。 使用getLastKnownLocation()作为可能的优化,但是否则需要requestLocationUpdates() ,然后使用onLocationChanged()方法中的位置。

有关更多信息,请参阅此示例项目和文档 。