Dec 9, 2011

How to track location

I would like to publish a sample code for tracking location on Java ME platform.

import javax.microedition.location.*;

public class LocationManager implements Runnable, LocationListener {
    private static final double DISTANCE = 100;

    private LocationProvider provider;
    private Location location;
    private Coordinates recentCoordinates;

    private int state = LocationProvider.TEMPORARILY_UNAVAILABLE;

    public LocationManager() {
        Thread thread = new Thread(this);
        thread.start();
    }

    public double getLatitude() {
        return location != null ? location.getQualifiedCoordinates().getLatitude() : 0;
    }

    public double getLongitude() {
        return location != null ? location.getQualifiedCoordinates().getLongitude() : 0;
    }

    ////////////////////////////////////////////////////////////////////////////

    public void locationUpdated(LocationProvider lp, Location location) {
        Coordinates currentCoordinates = location.getQualifiedCoordinates();
        if (recentCoordinates == null || currentCoordinates.distance(recentCoordinates) > DISTANCE) {
            // TODO: handle new location

            recentCoordinates = currentCoordinates;
        }
  
        this.location = location;
    }

    public void providerStateChanged(LocationProvider lp, int state) {
        this.state = state;
    }

    ////////////////////////////////////////////////////////////////////////////

    public void run() {
        try {
            init();
        }
        catch(LocationException e) {
            // TODO: handle me
        }
    }

    ////////////////////////////////////////////////////////////////////////////

    private void init() throws LocationException {
        Criteria criteria = new Criteria();
        criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);

        provider = LocationProvider.getInstance(criteria);
        provider.setLocationListener(this, -1, -1, -1);
    }

}

0 comments:

Post a Comment