Android locationManager.getLastKnownLocation(provider)一直未null的解决方案,亲测有效

最近在使用Android自带的LocationManager获取地理位置信息时,遇到在室内测试locationManager.getLastKnownLocation(provider)一直为空,至于权限之类的都在AndroidManifest.xml中配置了,并且也动态权限申请了,依旧为空很是头疼,最后实在StackOverflow上找到了答案,现在将解决过程记录一下。

第一次尝试通过 Criteria去获取还是为null:

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);// 允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗

        provider = locationManager.getBestProvider(criteria, true);
        if ("".equals(provider)) {
            return "当前设备无定位器";
        } else {
            Location location = locationManager.getLastKnownLocation(provider);
            }

第二次是通过遍历getAllProviders()获取provider还是为null:

   LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = locationManager.getAllProviders();//获取设备所有的定位器
        String provider = "";
        if (allProviders.contains(LocationManager.GPS_PROVIDER)) {//优先选用GPS定位
            provider = LocationManager.GPS_PROVIDER;
        } else if (allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        }else {
            provider=LocationManager.PASSIVE_PROVIDER;
        }

        Location location = locationManager.getLastKnownLocation(provider);

最终解决办法:通过以下方法遍历provider获取,完美解决,附上Stackoverflow的参考地址以及解决后的效果图

private Location getLastKnownLocation(LocationManager locationManager) {
        List<String> providers = locationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = locationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        return bestLocation;
    }

在这里插入图片描述

发布了41 篇原创文章 · 获赞 238 · 访问量 8万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章