getLastKnownLocation()返回null的解决
在使用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" />
LocationManager mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);Location location = mgr.getLastKnownLocation(bundle.getString("provider"));while(location == null){ mgr.requestLocationUpdates("gps", 60000, 1, locationListener);} /** * 这里一定要对LocationManager进行重新设置监听 * mgr获取provider的过程不是一次就能成功的 * mgr.getLastKnownLocation很可能返回null * 如果只在initProvider()中注册一次监听则基本很难成功 */@Overrideprotected void onResume() {super.onResume();mgr.requestLocationUpdates(bundle.getString("provider"), 60000, 1, locationListener);}@Overrideprotected void onPause() {super.onPause();mgr.removeUpdates(locationListener);}