getLastKnownLocation 返回null

在使用LocationManager.getLastKnownLocation("gps")獲取gps定位的過程當中總是報空指針異常

在網上百度查了很多資料發現這個問題多出如今2.0以上版本
解決方法可能是:
1.在AndroidManifest.xml中添加android

  
  
  
  
  1. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />     
  2. <uses-permission android:name="android.permission.INTERNET" />     
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />   

2.在emulator control中手動設置經緯度

可是個人程序這些都寫了依舊報空指針

後來在外國論壇上終於找到一些啓發
一個哥們這樣寫代碼ide

  
  
  
  
  1. LocationManager mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);      
  2. Location location = mgr.getLastKnownLocation(bundle.getString("provider"));      
  3. while(location  == null)      
  4. {      
  5.   mgr.requestLocationUpdates("gps"600001, locationListener);       
  6. }     

我試了一下還真有效,他的解釋是用debug發現getLastKnownLocation()方法不是一次就能定位的,必須屢次才能成功。

可是顯然這樣用循環一直等待很沒效率,因此我重寫了MapActivity的方法this

  
  
  
  
  1. @Override     
  2. protected void onResume() {      
  3.     super.onResume();      
  4.     mgr.requestLocationUpdates(bundle.getString("provider"), 600001, locationListener);      
  5. }      
  6.      
  7. @Override     
  8. protected void onPause() {      
  9.     super.onPause();      
  10.     mgr.removeUpdates(locationListener);      
  11. }     

在外國技術論壇上找了個解釋,我的感受很貼切:

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

相關文章
相關標籤/搜索