android onLocationChanged never called

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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;         }          @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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!