Code sample: Using the Location class to retrieve GPS location information

import javax.microedition.location.*;

public class handleGPS
{
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;
    static float  heading;
    static float  velocity;
    static long   timeStamp;
    static String nmeaString;

    public handleGPS()
    {
        gpsThread = new GPSThread();
        gpsThread.start();
    }

    private static class GPSThread extends Thread
    {
        public void run()
        {
            Criteria myCriteria = new Criteria();
            myCriteria.setCostAllowed(false);

            try
            {
                LocationProvider myLocationProvider =
                    LocationProvider.getInstance(myCriteria);

                try
                {
                    Location myLocation = myLocationProvider.getLocation(300);

                    latitude   = myLocation.getQualifiedCoordinates().getLatitude();
                    longitude  = myLocation.getQualifiedCoordinates().getLongitude();
                    velocity   = myLocation.getSpeed();
                    heading    = myLocation.getCourse();
                    timeStamp  = myLocation.getTimestamp();
                    nmeaString = myLocation.getExtraInfo
                        ("application/X-jsr179-location-nmea");
                }
                catch ( InterruptedException iex )
                {
                    return;
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( LocationException lex )
            {
                return;
            }

            return;
        }
    }
}

Was this information helpful? Send us your comments.