2013-07-09 42 views
6

我正在開發一個Android應用程序,其中當前和精確的位置是關鍵。在檢測到GPS定位後,它將轉到下一個活動。Android:只獲取最近的位置,而不是getLastKnownLocation?

問題是我在戶外測試過它,發現有時它只是使用以前修復程序中的位置。

所以我在問什麼;除了通過getLastKnownLocation之外,是否還有其他邏輯從LocationManager獲取位置?我還沒有找到一個看起來不像

Location location = locationManager.getLastKnownLocation(provider); 

Thanx!

回答

2

下面是來自official guide示例代碼(帶小的修改):

// Acquire a reference to the system Location Manager 
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

// Define a listener that responds to location updates 
LocationListener locationListener = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     makeUseOfNewLocation(location); 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) {} 
    public void onProviderEnabled(String provider) {} 
    public void onProviderDisabled(String provider) {} 
    }; 

// Register the listener with the Location Manager to receive location updates 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 

在這裏,你剛剛從GPS請求更新,並儘快收到的位置,你會得到一個回調呼叫。

+0

這是爲我做的!當然,就我而言,我沒有或需要位置,直到它_changes_。如果我從'onLocationChanged'調用我的下一個方法,我甚至不需要聽GPS定位。感謝名單! – dhafnar

+0

我做了同樣的代碼..但onLocationChanged()永遠不會被調用..我不知道是什麼問題 –

2

您可以使用LocationListener,然後致電locationManager.requestLocationUpdates()傳遞您自己的偵聽器實現。

1

谷歌已經發布了新的位置API,檢查此鏈接了https://developer.android.com/training/location/index.html

你的問題,你需要實現位置更新回調以獲取當前位置。 https://developer.android.com/training/location/receive-location-updates.html

+0

我測試了新的Location API,您不需要指定位置提供程序來獲取位置更新了。 LocationClient會爲您獲取位置更新(如iOS)。在新的API中,您只需使用LocationRequest來設置服務參數,如更新間隔,位置準確性。然後讓LocaitonClient檢索位置更新。 – pkliang

相關問題