onLocationChanged不会自动调用

use*_*051 11 gps android geolocation locationmanager locationlistener

我在Android中的onLocationChanged事件有问题.这是触发:

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

这是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));
}
Run Code Online (Sandbox Code Playgroud)

因此,onLocationChanged仅在我按"start"后调用一次.它应该在每次位置发生变化时自动调用,对吗?就我而言,事实并非如此.
请帮我.

use*_*051 8

问题似乎已经解决了.在onCreate中,我补充说:

Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
best = mgr.getBestProvider(crit, false);
mgr.requestLocationUpdates(best, 0, 1, locationListener);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

另外,非常重要的方法:

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

@Override
protected void onPause() {
    super.onPause();
    mgr.removeUpdates(locationListener);
}
Run Code Online (Sandbox Code Playgroud)

还有一些新的权限:

<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" />
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`ACCESS_FINE_LOCATION`,则不需要"ACCESS_COARSE_LOCATION".只为你知道;) (10认同)
  • @gumuruh,因为`ACCESS_FINE_LOCATION`包括WiFi,小区和GPS位置和`ACCESS_COARSE_LOCATION`仅包括小区和WiFi.所以第一个许可基本上包括第二个许可. (4认同)