Android(安卓)解决 GetLastKnownLocation(provider) = null
16lz
2021-01-26
事情的起因就是我用系统的GetLastKnownLocation输出结果永远是null。后来看大家说这个方法在室内90%都不管用。
于是查了国内各大网站给出了两个解决办法:
1.while(GetLastKnownLocation(provider) = null){
GetLastKnownLocation = null
}
2.locationManager.setTestProviderEnabled(provider1, false);
然而这两种方法并没能解决我的问题。只是疯狂在while里循环,知道我的App崩溃。。。
最后查询StackOverflow得到解决办法。
用如下办法获取Last Location
LocationManager mLocationManager;Location myLocation = getLastKnownLocation();private Location getLastKnownLocation() { mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location bestLocation = null; for (String provider : providers) { Location l = mLocationManager.getLastKnownLocation(provider); if (l == null) { continue; } if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { // Found best last known location: %s", l); bestLocation = l; } } return bestLocation;}
结果很成功。
激动之余记录一下,并分享给大家。
原文链接:https://stackoverflow.com/questions/20438627/getlastknownlocation-returns-null
更多相关文章
- android fragment 重复创建的问题
- Android(安卓)Studio 图片资源存放位置 + drawable文件夹的创建
- [android] 构建menu的一种方法
- EventBus两个Activity传值
- Android(安卓)API Demos学习 - Service部分
- Android(安卓)各层中日志打印功能的应用
- Android中简单调用图片、视频、音频、录音和拍照的方法
- android自定义title的方法
- Android中定时器的使用(Timer)