簡體   English   中英

Android用戶位置的緯度和經度返回0.0

[英]Android User Location returning 0.0 for latitude and longitude

我有一個類對象,可檢索用戶的緯度和經度。 在我的UI線程中,我在創建Activity的onCreate方法中創建對象:

userLocation = new UserLocation(this);

這是課程片段:

public UserLocation(Context mContext) {
    //Pass parameter to class field:
    this.mContext = mContext;
    //Fetch the user's location:
    fetchUserLocation();
}

public void fetchUserLocation() {
    // Acquire a reference to the system Location Manager:
    LocationManager locationManager = (LocationManager)this.mContext.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates:
    LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        //Manage the data recieved:
        makeUseOfLocation(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.NETWORK_PROVIDER, 0, 0, locationListener);
}

private void makeUseOfLocation(Location location) {
    //Split the data of the location object:
    userLatitude = location.getLatitude();                      
    userLongitude = location.getLongitude();                    

}

/**
 * @return userLatitude
 */
public double getLatitude() {
    return userLatitude;
}

/**
 * @return userLongitude
 */
public double getLongitude() {
    return userLongitude;
}

現在回到主線程中,當按下按鈕時,將收集緯度和經度:

    // GET THE LATITUDE AND LONGITUDE OF THE USER:
    currentLatitude  = userLocation.getLatitude();
    currentLongitude = userLocation.getLongitude();

現在說我啟動該應用程序,如果我立即按下該按鈕,則緯度和經度的接收值為0.0。

但是,如果我啟動該應用程序並等待4-5秒鍾,然后按按鈕,則將收到正確的值。

誰能告訴我這種現象的原因嗎?

我在編寫一種方法時注意到了這一點,當用戶啟動應用程序時,如果字段為null,則收集緯度和經度。 那么這反過來又返回了不利的0.0值。

謝謝!

誰能告訴我這種現象的原因嗎?

好吧-是的-大概在顯示0、0時,尚未調用onLocationChanged因為尚無法立即知道該位置。 您已要求位置管理器在知道位置后給您回電-這與立即獲取位置不同。

如果您不希望在知道位置之前向用戶報告位置,則應記住是否已調用onLocationChanged (或可能上次調用也可能被調用,以避免顯示陳舊數據)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM