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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章