Search code examples
androidgeolocationlocationlistenerandengine

Using a LocationListener alongside the AndEngine game engine


Hey, I'm currently looking into how to use AndEngine together with the phone's GPS location. I figured it shouldn't be too hard to access this information, so I just grabbed the ChangeableText example and am trying to tweak it so I can see that it grabs the Location correctly, basically what I have done is:

added 'implements LocationListener' to the class declaration

    public class ChangeableTextExample extends BaseExample implements LocationListener{

added location variables and a location manager to the class fields:

private long curlat;
private long curlng;
private LocationManager locationManager;

instantiated the locationManager in the onLoadScene() method:

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

set the elapsedText to print out the curlat and curlng variables:

     scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() {
        public void onTimePassed(final TimerHandler pTimerHandler) {
            elapsedText.setText("Location: " + curlat + ", " + curlng);
            fpsText.setText("FPS: " + fpsCounter.getFPS());
        }
    }));

and implement the onLocationChanged(Location arg) method so that it updates the curlat,curlng fields.

public void onLocationChanged(Location location) {
    this.curlat = (long) (location.getLatitude()*1E6);
    this.curlng = (long) (location.getLongitude()*1E6);     
}

Sadly, this doesn't work, and I was wondering if any of you could point me in the right direction? I'm pretty new to programming for Android, and even newer to programming with AndEngine. I'm guessing it has something to do with the fact that the locationManager isn't properly instantiated?

Thanks!


Solution

  • See Android - obtaining user location.

    You have to actually tell the locationManager object to give you updates (as well as put a permission in the AndroidManifest.xml for location information).

    From the link, here's the stuff you're missing:

    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    

    For the AndroidManifest.xml ( you may have to change the permission if you'd rather juts use only the less accurate network/wifi location stuff instead of GPS):

    <manifest ... >
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        ...
    </manifest>