【问题标题】:Android location: get first locationAndroid位置:获取第一个位置
【发布时间】:2014-12-22 06:01:35
【问题描述】:

获得第一个位置时我需要计算一些东西(它不需要非常准确)。

我有一个 LocationManager 和一个 LocationListener,直到现在我有一个布尔值 firstTime,它最初为 true,第一次调用 onlocationChanged 时我将其设置为 false。但每次调用 onlocationChanged 方法时(每 5 秒),我都会检查 firstTime 是否为假。

这个解决方案并不能真正让我满意,有没有更好的方法来检查首次事件? (这个问题可能在更大的背景下,不仅仅是 GPS 位置)。

我将提供一些代码以便更好地理解:

boolean firstLocation = true;
LocationManager locManager = (LocationManager) context
        .getSystemService(Context.LOCATION_SERVICE);

LocationListener locListener = new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {
        if (firstLocation == true) {
            sights = getListForLocation(location, GPS_INITIAL_PERIMETER);
            firstLocation = false;
        }
        // do something everytime onLocationChanged is called

    }
};

/**
 * starts the listener for GPS-Positions
 */
public void start() {
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            GPS_UPDATE_TIME, GPS_UPDATE_DISTANCE, locListener);
}

如您所见,我只需要在第一次获得新位置时做某事。

【问题讨论】:

    标签: android gps locationmanager


    【解决方案1】:

    用 null 初始化你的位置并检查它:

    if(lastKnownLocation == null)
    {
        //first time
    }
    

    然后在 LocationListener 上做:

    @Override
    public void onLocationChanged(Location location) 
    {
        lastKnownLocation = location;
    }
    

    【讨论】:

    • 我不明白 if(lastKnownLocation == null) 在哪里执行?我不想执行超过一次。
    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2016-03-18
    • 2018-02-08
    • 1970-01-01
    • 2018-02-14
    • 2016-09-23
    相关资源
    最近更新 更多