Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

android - onLocationChanged is not called automatically

I have a problem with onLocationChanged event in Android. Here's the triggering:

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

And here's the onLocationChanged method:

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

So, onLocationChanged is called only once and only after I press "start". It's supposed to be called automatically every time the location has changed, right? In my case, it's not.
Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem seems to be solved. In onCreate, I added:

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

onLocationChanged now looks like that:

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

Also, very important methods:

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

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

And also some new permissions:

<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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...