在使用LocationManager.getLastKnownLocation("gps")獲取gps定位的過程當中總是報空指針異常
在網上百度查了很多資料發現這個問題多出如今2.0以上版本
解決方法可能是:
1.在AndroidManifest.xml中添加android
- <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中手動設置經緯度
可是個人程序這些都寫了依舊報空指針
後來在外國論壇上終於找到一些啓發
一個哥們這樣寫代碼ide
- 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的方法this
- @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.idea