Android通过位置管理器获取经度和纬度 [英] Android Get latitude and longitude with location manager

查看:165
本文介绍了Android通过位置管理器获取经度和纬度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过位置管理器获取用户位置,但位置始终返回空值。我还要求用户打开GPS。



这是我的代码:

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

if(permisioncheck == 0){

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

列表< String> providers = lm.getProviders(true);

位置bestLocation = null;

(String provider:providers){
Location location = lm.getLastKnownLocation(provider);
if(location == null){
continue; (bestLocation == null || location.getAccuracy())< bestLocation.getAccuracy()){
//找到最好的最后一个已知位置:%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()方法中。

请参阅本示例项目文档以获取更多信息。


I'm trying to get the user location with location manager but the location always returns null. I also am asking to the user to turn on the gps.

This is my code:

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

I hope that someone could help me to find the error, thanks.

解决方案

The "error" is that you are assuming that getLastKnownLocation() will return a Location. Frequently, it will return null. Use getLastKnownLocation() as a possible optimization, but otherwise you need to requestLocationUpdates(), then use the location in the onLocationChanged() method.

See this sample project and the documentation for more.

这篇关于Android通过位置管理器获取经度和纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆