开发者

android onLocationChanged never called

开发者 https://www.devze.com 2023-03-27 01:26 出处:网络
I\'ve implemented code that should return present location. First the code: public static double[] getLocation(Context context) {

I've implemented code that should return present location.

First the code:

public static double[] getLocation(Context context) {
        double[] result;
        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        MyLocationListener ll = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

        while(!hasLocation) { }

        result = ll.getResult();

        return result;
    }

    private static class MyLocationListener implements LocationListener {
        double[] result = new double[2];

        public double[] getResult() {
            return result;
      开发者_如何学JAVA  }

        @Override
        public void onLocationChanged(Location location) {
            if(location.getAccuracy() != 0.0 && location.getAccuracy() < 100) {
                result[0] = location.getLatitude();
                result[1] = location.getLongitude();
                hasLocation = true;
                lm.removeUpdates(this);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onProviderEnabled(String provider) {}

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

The problem is that all stopps on 'while' statement. WHen I've tried to debug this setting breakpoint on the first line in onLocationChanged() nothing happens, but Logcat was showing some logs like:

loc_eng_report_position: vertical_accuracy = 64.000000
DEBUG/libloc(1292): date:2011-08-11, time:10:51:03.372, raw_sec=1313052663, raw_sec2=1313052663,raw_msec=1313052663372

Any ideas?


The while(!hasLocation) {} is blocking your application from doing anything. You'll either need to deal with the location in the callback onLocationChanged, or you'll need to start the location manager a lot earlier and hope that you have a result by the time you need it. You can't busy-wait for the answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消