【问题标题】:android onLocationChanged never calledandroid onLocationChanged 从未调用过
【发布时间】:2011-08-11 09:27:46
【问题描述】:

我已经实现了应该返回当前位置的代码。

首先是代码:

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) {}
    }

问题是所有的'while'语句都停止了。当我尝试在 onLocationChanged() 的第一行调试此设置断点时,没有任何反应,但 Logcat 显示了一些日志,例如:

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

有什么想法吗?

【问题讨论】:

    标签: android gps locationlistener


    【解决方案1】:

    while(!hasLocation) {} 正在阻止您的应用程序执行任何操作。您要么需要在回调 onLocationChanged 中处理位置,要么需要更早地启动位置管理器并希望在需要时得到结果。你不能忙——等待答案。

    【讨论】:

    • 我想用线程等待获取位置,然后返回结果。我应该将 requestLocationUpdates() 移动到单独的线程吗?
    • 好的,我用 Looper 把它移到了单独的线程中。现在它正在工作。删除更新仍然存在问题。 GPS 图标消失得太慢。不知道为什么。无论如何,谢谢你的建议:-)
    猜你喜欢
    • 2012-08-30
    • 2014-11-23
    • 2017-08-27
    • 2012-08-09
    • 1970-01-01
    • 2023-03-13
    • 2013-07-25
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多