2013-04-22 102 views
0

我試圖獲取位置和代碼的工作原理,但它不能正常工作。這裏是我的代碼Android get Location無法正常工作

// Get the location manager 
    LocationManager locationManager = (LocationManager)     
    getSystemService(LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    String bestProvider = locationManager.getBestProvider(criteria, false); 
    Location location = locationManager.getLastKnownLocation(bestProvider); 

    try { 
     lat = (int)Math.round((location.getLatitude() * 1e6)) ; 
     lon = (int)Math.round((location.getLongitude() * 1e6)) ; 
    } 
    catch (NullPointerException e){ 
     lat = -1; 
     lon = -1; 
    } 

的問題,當使用foursqure或Facebook IM是他們直接拿到的位置,但我的應用程序返回-1,-1(有時),有時正確查找位置。什麼可能是問題,或者我該如何改進以獲得更好的當前位置?謝謝

回答

0

對getLastKnownLocation的調用有時返回null,如Andorid documentation中指定的那樣。所以有時候這個代碼的確會產生lat = lon = -1。另外,getBestProvider是確定最能滿足給定條件的提供者的一種方法。由於您沒有指定任何標準,合乎邏輯的結論是所有提供商都同樣好,所以結果可能是隨機的。最後,請注意lat = -1和lon = -1是一個有效的位置,所以通常不是標記錯誤的好方法。

正如在這裏的另一個答案建議,你應該實現http://developer.android.com/reference/android/location/LocationListener.html。然後你有問題要使用哪些提供者。我的方法是全部使用它們並使用簡單的卡爾曼濾波器來處理不同提供者在不同時間具有不同準確度的事實。我發佈了這裏使用的簡單卡爾曼濾波器Smooth GPS data