Android 位置正在返回空LocationManager.getlastlocation Gps提供程序
我已经搜索并实现了各种方法来获取我的位置。但不管我做什么,位置总是空的。它是空的。我的应用程序几乎完成了,这是唯一的问题是我的代码Android 位置正在返回空LocationManager.getlastlocation Gps提供程序,android,gps,google-maps-android-api-2,Android,Gps,Google Maps Android Api 2,我已经搜索并实现了各种方法来获取我的位置。但不管我做什么,位置总是空的。它是空的。我的应用程序几乎完成了,这是唯一的问题是我的代码 public Location getlocation() { Location loc = null; LocationManager lm = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.
public Location getlocation() {
Location loc = null;
LocationManager lm = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
return loc;
}
@Override
public void onMapReady(GoogleMap googleMap) {
setmap(googleMap);
}
public void setmap(final GoogleMap map) {
googlemap = map;
if (googlemap != null) {
if (sharedPreferences.getBoolean(CustomAlarm.satellite, false)) {
googlemap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} else {
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
if(getlocation() == null){
Toast.makeText(getContext(),"You don't live on this earth or Location null",Toast.LENGTH_LONG).show();
}
在评论之前,请注意这一点
1-我正在我的手机上调试三星j1 api级别19
2-已启用位置和gps
3-尝试在谷歌地图中定位我的位置
4-还启用了谷歌位置历史记录
但是请不要帮忙。曾经有过同样的问题。
我通过请求位置更新解决了这个问题
过了一段时间后,位置被捕获。您正在请求此文件中的位置
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { }
这意味着如果权限未被授予
行loc=lm.getlastnownlocation(LocationManager.GPS\u提供者)当权限被授予时(可能是这样),代码>将永远不会执行,因此将保持与您先前分配给它的值相同Location loc=null代码>所以为空
您应该将if语句更改为
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
这意味着,如果位置权限已授予,则向我提供位置。然后lm.isProviderEnabled(LocationManager.GPS\u PROVIDER)
返回false。您不能检查loc=lm.getlastnownlocation(LocationManager.GPS\u提供程序)是否正确吗代码>行被执行了吗?只是添加了一个检查语句,它不是false。因此,行loc=lm.getLastKnownLocation(LocationManager.GPS\u PROVIDER)代码>被执行?但它不是在之前,对吗?因为你变了!=to==在第一个if语句中,所以我不知道如果你当时没有检查它,你怎么能这么肯定。。。无论如何,唯一的方法是loc=lm.getlastnownlocation(LocationManager.GPS\u提供者)当未启用LocationManager.GPS\U提供程序时,code>将返回null。