原文地址:getLastKnownLocation()返回null的解决作者:luckzr
在应用 LocationManager.getLastKnownLocation("gps")获取gps定位的历程中老是报空指针异常
在网上百度查了不少材料创造这个问题多出现在2.0以上版本
解决法子 多是:
1.在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2.在emulator control中手动设置经纬度
但是我的程序这些都写了依旧报空指针
后来在外国论坛上终于找到一些启迪
一个哥们这样写代码
LocationManager mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = mgr.getLastKnownLocation(bundle.getString("provider")); while(location == null) { mgr.requestLocationUpdates("gps", 60000, 1, locationListener); }
我试了一下还真有效,他的解释 是用debug创造getLastKnownLocation()法子 不是一次就能定位的,必须 多次才干成功 。
但是显然这样用循环一直等候很没效率 ,所以我重写了MapActivity的法子
@Override protected void onResume() { super.onResume(); mgr.requestLocationUpdates(bundle.getString("provider"), 60000, 1, locationListener); } @Override protected void onPause() { super.onPause(); mgr.removeUpdates(locationListener); }
一样也成功 了。。
在外国技巧论坛上找了个解释 ,个人感到很贴切:
The call to request update for a location is not blocking, hence it wont wait there. Also the provider in emulator may not have been started.
A possible check could be to see if the settings in it disable gps provider then send geo fix.
However, I would use Location Listener, it would be ideal in your case since you need a geo fix to proceed further.Location Listener is Used for receiving notifications from the LocationManager when the location has changed. You can unregister the listener after first geofix.
Note: It can take some time on device to get current location, and even on device this can return null.
原为引用:http://51jsp.cn/html/tuijianshujiyuedu/2010/0715/24521.html
转载于:https://blog.51cto.com/chengyou/1663494