【问题标题】:Wait for a value to be set to true等待将值设置为 true
【发布时间】:2012-06-16 14:09:47
【问题描述】:

我希望我的代码等待 mGPS.GotLocaton 为真(在触发 onLocationChanged 事件时设置)

public class GPSManager  {
    Context MyContext;
    boolean GotLocation = false;
    Location CurrentLocation;
    LocationManager locationManager;

    LocationListener locationlistener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            GotLocation = true;
            locationManager.removeUpdates(locationlistener);
        }

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

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };

    public GPSManager(Context context){
        this.MyContext = context;
        locationManager = (LocationManager) MyContext.getSystemService(Context.LOCATION_SERVICE);
    }

    public void GetCurrentLocation(){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistener);
        GotLocation = false;
    }
}

被调用者:

    myGPS.GetCurrentLocation();
    do{
    }while (!myGPS.GotLocation);

但它不会等待/循环 - 我错过了什么。

【问题讨论】:

  • 看起来像 Android 代码所以添加了 android 标签

标签: android gps location wait android-location


【解决方案1】:

可能是因为您在添加LocationListener 时已立即收到位置响应。

那是一些奇怪的代码。考虑改用回调。

有关位置信息的更多信息,请参阅此 android 开发者博客条目:

http://android-developers.blogspot.co.uk/2011/06/deep-dive-into-location.html

或者更好的是,使用这个为您解决所有问题的库:

http://code.google.com/p/little-fluffy-location-library/

【讨论】:

  • 他的代码也很脏,我不明白他为什么在 onLocationChanged 中调用 removeUpdates。
  • 也不确定,但也许他只想更新一个位置。
  • @Mattias = 你的明星为什么不是谷歌搜索顶部的 Little-Fluffy 位置库会为我节省几个小时!!!
  • 如果您喜欢这个答案,请随意投票并接受您的问题的答案;-)
【解决方案2】:

你在哪个线程调用获取位置的循环?

如果它在主线程中,这是非常错误的,因为 locationlistener 只会让事件在这个线程上运行,但是由于这个线程在循环中,它永远不会到达那里,所以你处于无限循环中,这也大约 5 秒左右会导致 ANR。

locationlistener 的工作方式是使用观察者设计模式——当它有东西可以给你时,它就会给你。你不能简单地一次又一次地问它。您可以使用的唯一类似的方法是使用 getLastKnownLocation 获取它的最后一个位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    相关资源
    最近更新 更多