getLastKnownLocation返回null

我已经阅读了有关此问题的一些问题,但并没有找到我需要的答案。


因此,情况是我已经设置了地图,并且想要获取当前的GPS位置。我检查过我的变量不是NULL,但是我的结果是:


getLastKnownLocation(provider, false);

虽然给我null,所以这是我需要帮助的地方。我已经添加了对COARSE + FINE位置的权限。但是我通常会禁用手机的各种网络数据,因为我对手机账单中不可预测的数据流费用感到不满意。因此,此测试仅启用并连接了WiFi。


为了使之成为可能,我还需要启用更多功能吗?我认为WiFi应该足够了吗?


慕勒3428872
浏览 573回答 3
3回答

潇潇雨雨

使用此方法获取最近的已知位置:LocationManager mLocationManager;Location myLocation = getLastKnownLocation();private Location getLastKnownLocation() {&nbsp; &nbsp; mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);&nbsp; &nbsp; List<String> providers = mLocationManager.getProviders(true);&nbsp; &nbsp; Location bestLocation = null;&nbsp; &nbsp; for (String provider : providers) {&nbsp; &nbsp; &nbsp; &nbsp; Location l = mLocationManager.getLastKnownLocation(provider);&nbsp; &nbsp; &nbsp; &nbsp; if (l == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Found best last known location: %s", l);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bestLocation = l;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return bestLocation;}

慕的地10843

试试这个对我有用:-LocationManager mLocationManager;Location myLocation = getLastKnownLocation();&nbsp; &nbsp; &nbsp; &nbsp; private Location getLastKnownLocation() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Location oldLoc;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (true){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; oldLoc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (oldLoc == null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return oldLoc;&nbsp; &nbsp; &nbsp; &nbsp; }您可以使用NETWORK_PROVIDER代替GPS_PROVIDER以获得更快的结果。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android