【问题标题】:Android Get latitude and longitude with location manager [duplicate]Android使用位置管理器获取纬度和经度[重复]
【发布时间】:2017-04-13 15:51:29
【问题描述】:

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

这是我的代码:

   int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);

    if(permisioncheck == 0){

        lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);

        List<String> 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);
    }

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

【问题讨论】:

  • @OusmaneMahyDiaw 我还必须在我的问题中添加什么?实际上这是我所有的代码

标签: java android gps location


【解决方案1】:

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

请参阅this sample projectthe documentation 了解更多信息。

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多