getLastKnownLocation 返回null
在使用LocationManager.getLastKnownLocation("gps")獲取gps定位的過程中老是報空指標異常
在網上百度查了不少資料發現這個問題多出現在2.0以上版本
解決方法多是:
1.在AndroidManifest.xml中新增
- <uses-permission="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permissionandroid:name="android.permission.INTERNET"/>
-
<uses-permissionandroid:name
- <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permissionandroid:name="android.permission.INTERNET"/>
- <uses-permissionandroid: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);
- }
-
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的方法
- /**
- * 這裡一定要對LocationManager進行重新設定監聽
- * mgr獲取provider的過程不是一次就能成功的
- * mgr.getLastKnownLocation很可能返回null
- * 如果只在initProvider()中註冊一次監聽則基本很難成功
- */
- @Override
- protectedvoid onResume() {
- super.onResume();
- mgr.requestLocationUpdates(bundle.getString("provider"), 60000, 1, locationListener);
- }
- @Override
- protectedvoid onPause() {
- super.onPause();
- mgr.removeUpdates(locationListener);
- }
- /**
- * 這裡一定要對LocationManager進行重新設定監聽
- * mgr獲取provider的過程不是一次就能成功的
- * mgr.getLastKnownLocation很可能返回null
- * 如果只在initProvider()中註冊一次監聽則基本很難成功
- */
- @Override
- protectedvoid onResume() {
- super.onResume();
- mgr.requestLocationUpdates(bundle.getString("provider"), 60000, 1, locationListener);
- }
- @Override
- protectedvoid 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://blog.csdn.net/L_serein/article/details/6127300