1. 程式人生 > >Android GPS getLastKnownLocation()返回null的解決

Android GPS getLastKnownLocation()返回null的解決

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

在網上百度查了不少資料發現這個問題多出現在2.0以上版本
解決方法多是:
1.在AndroidManifest.xml中新增
Xml程式碼  收藏程式碼
  1. <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
  2. <uses-permissionandroid:name="android.permission.INTERNET"/>
  3. <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>

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

但是我的程式這些都寫了依舊報空指標

後來在外國論壇上終於找到一些啟發
一個哥們這樣寫程式碼
Java程式碼  收藏程式碼
  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. }  
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的方法
Java程式碼  收藏程式碼
  1. /** 
  2.     * 這裡一定要對LocationManager進行重新設定監聽 
  3.     * mgr獲取provider的過程不是一次就能成功的 
  4.     * mgr.getLastKnownLocation很可能返回null 
  5.     * 如果只在initProvider()中註冊一次監聽則基本很難成功 
  6.     */
  7. @Override
  8. protectedvoid onResume() {  
  9.     super.onResume();  
  10.     mgr.requestLocationUpdates(bundle.getString("provider"), 600001, locationListener);  
  11. }  
  12. @Override
  13. protectedvoid onPause() {  
  14.     super.onPause();  
  15.     mgr.removeUpdates(locationListener);  
  16. }  
   /**
     * 這裡一定要對LocationManager進行重新設定監聽
     * mgr獲取provider的過程不是一次就能成功的
     * mgr.getLastKnownLocation很可能返回null
     * 如果只在initProvider()中註冊一次監聽則基本很難成功
     */
	@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://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-returns-null