【问题标题】:onLocationChanged is not called automaticallyonLocationChanged 不会自动调用
【发布时间】:2011-12-09 15:39:03
【问题描述】:

我对 Android 中的 onLocationChanged 事件有疑问。这是触发:

case R.id.start: {
    Points.add(overlay.getMyLocation()); // Points' type is ArrayList<GeoPoint>
    mgr.requestLocationUpdates(best, 0, 3, locationListener);
    }
    break;

这里是 onLocationChanged 方法:

public void onLocationChanged(Location location) {
    i++;
    Points.add(overlay.getMyLocation());
    MapOverlay mapOverlay = new MapOverlay(Points.get(i-1), Points.get(i));
    map.getOverlays().add(mapOverlay); //does the drawing
    mMapController.animateTo(Points.get(i));
}

因此,onLocationChanged 仅在我按下“开始”后才被调用一次。它应该在每次位置发生变化时自动调用,对吧?在我的情况下,它不是。
请帮帮我。

【问题讨论】:

  • 您是否将使用位置服务的权限添加到清单中,如下所示:&lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt;
  • 当然,这是我的权限部分:
  • 虽然已经很晚了但是希望这个评论可以帮到别人,看看这个链接:lengrand.fr/2013/10/…

标签: android geolocation gps locationmanager locationlistener


【解决方案1】:

问题似乎解决了。 在 onCreate 中,我添加了:

Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
best = mgr.getBestProvider(crit, false);
mgr.requestLocationUpdates(best, 0, 1, locationListener);

onLocationChanged 现在看起来像这样:

@Override
public void onLocationChanged(Location location) {
    i++;
    nextPoint = overlay.getMyLocation();
    latitude = nextPoint.getLatitudeE6();
    longtitude = nextPoint.getLongitudeE6();
    lastPoint = new GeoPoint((int) latitude, (int) longtitude);
    Points.add(lastPoint);
    MapOverlay mapOverlay = new MapOverlay(Points.get(i - 1), Points.get(i));
    map.getOverlays().add(mapOverlay);
    mMapController.animateTo(Points.get(i));
    nextPoint = null;
    lastPoint = null;
}

另外,非常重要的方法:

@Override
protected void onResume() {
    super.onResume();
    mgr.requestLocationUpdates(best, 10000, 1, locationListener);
}

@Override
protected void onPause() {
    super.onPause();
    mgr.removeUpdates(locationListener);
}

还有一些新的权限:

<uses-permission android:name="android.permission.ACCESS_GPS" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />

【讨论】:

  • 如果您使用ACCESS_FINE_LOCATION,则不需要ACCESS_COARSE_LOCATION。只是为了让你知道;)
  • @lomza,有什么区别?
  • @gumuruh,因为ACCESS_FINE_LOCATION 包括 WiFi、蜂窝和 GPS 位置,而ACCESS_COARSE_LOCATION 仅包括蜂窝和 WiFi。所以第一个权限基本上包括第二个。
  • @lomza,这是很好的说明。谢谢你。我只是从你那里知道的。 :D
  • @RaviVaniya mgr 是您可以使用locationManager = (LocationManager) requireContext().getSystemService(Context.LOCATION_SERVICE); 获取的 LocationManager - locationListener 是您对 Android LocationListener 接口的实现,best 是包含名称的 String最符合您通过的标准的提供者。
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 2023-03-18
  • 2013-01-02
  • 2017-01-20
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
相关资源
最近更新 更多