Development Guide

Local Navigation

Retrieving the location of a BlackBerry device

You can retrieve the location of a BlackBerry device by specifying a single GPS fix, or by specifying a location listener to retrieve continuous GPS fixes.

Retrieve the location of a BlackBerry device

  1. Import the required classes.
    import javax.microedition.location.*;
  2. Create a class and a constructor.
    public class handleGPS
    {
       public handleGPS()
       {
       }
    }
  3. Declare static fields in the class.
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;
  4. In the constructor, create and start a local thread.
    gpsThread = new GPSThread();
    gpsThread.start();
  5. In the class, create a private class that extends Thread, and create a run() method.
    private class GPSThread extends Thread
    {
       public void run()
       {
       }
    }
  6. In the run() method, create an instance of the Criteria class. Invoke setCostAllowed(false) to specify that the autonomous mode.
    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
  7. In the run() method, create a try/catch block. In the block create a LocationProvider object by getting an instance of the Criteria object. Create another try/catch block to create a Location object to request the current location of the BlackBerry device and specify the timeout period in seconds. When the getLocation() method returns, request the latitude and longitude coordinates.
    try
    {
        LocationProvider myLocationProvider =
            LocationProvider.getInstance(myCriteria);
    
        try
        {
            Location myLocation = myLocationProvider.getLocation(300);
            latitude  = myLocation.getQualifiedCoordinates().getLatitude();
            longitude = myLocation.getQualifiedCoordinates().getLongitude();
        }
        catch ( InterruptedException iex )
        {
            return;
        }
        catch ( LocationException lex )
        {
            return;
        }
    }
    catch ( LocationException lex )
    {
        return;
    }
    return;
Back To Top

Code sample: Retrieving the GPS location of a BlackBerry device

import javax.microedition.location.*;

public class handleGPS
{
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;

    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();
                }
                catch ( InterruptedException iex )
                {
                    return;
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( LocationException lex )
            {
                return;
            }
            return;
        }
    }
}
Back To Top

Retrieve the location of a BlackBerry device by specifying continuous fix requests

You can use the Location API to retrieve location information of a BlackBerry device at any interval.
  1. Import the required classes and interface.
    import javax.microedition.location.*;
  2. Create a class and a constructor.
    public class handleGPS
    {
        public handleGPS()
        {
        }
    }
  3. In the constructor, create an instance of the Criteria class. Create a try/catch block. In this block, create an instance of the LocationProvider class by invoking getInstance() and using the Criteria object. Invoke setLocationListener() to specify the location of the GPS event listener.
    Criteria myCriteria = new Criteria();
    
    try
    {
        LocationProvider provider = LocationProvider.getInstance(myCriteria);
        provider.setLocationListener(new handleGPSListener(), 10, -1, -1);
    }
    catch ( LocationException lex )
    {
        return;
    }
  4. In the class, implement the LocationListener interface. You must add functionality as required to this implementation.
    public static class handleGPSListener implements LocationListener
    {
       public void locationUpdated(LocationProvider provider, Location location)
       {
          if (location.isValid())
          {
              // do something
          }
          else
          {
              // invalid locatuon
          }
       }
    
       public void providerStateChanged(LocationProvider provider, int newState)
       {
          if (newState == LocationProvider.OUT_OF_SERVICE)
          {}
          else if (newState == Location.TEMPORARILY_UNAVAILABLE )
          {}
       }
    }
Back To Top

Code sample: Retrieving the GPS location of a BlackBerry device by using continuous fix requests

import javax.microedition.location.*;

public class handleGPS
{
    public handleGPS()
    {
        Criteria myCriteria = new Criteria();

        try
        {
            LocationProvider provider = LocationProvider.getInstance(myCriteria);
            provider.setLocationListener(new handleGPSListener(), 10, -1, -1);
        }
        catch ( LocationException lex )
        {
            return;
        }
    }

    public static class handleGPSListener implements LocationListener
    {
        public void locationUpdated(LocationProvider provider, Location location)
        {
            if (location.isValid())
            {
                // do something
            }
            else
            {
                // invalid location
            }
        }

        public void providerStateChanged(LocationProvider provider, int newState)
        {
            if (newState == LocationProvider.OUT_OF_SERVICE)
            {
                // GPS unavailable due to IT policy specification
            }
            else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE )
            {
                // no GPS fix
            }
        }
    }
}
Back To Top

Retrieving location information by using the Location class

You can use the JSR 179 Location API, which is provided in the javax.microedition.location.Location package, to retrieve the following information:

  • latitude as a double
  • longitude as a double
  • ground speed of the BlackBerry device, in meters per second
  • course of the BlackBerry device, in degrees relative to true north
  • time stamp of the GPS fix
  • NMEA sentence that contains the number of satellites that a BlackBerry device tracks
Back To Top

Retrieve location information by using the Location class

You can request a GPS fix and then retrieve the latitude, longitude, velocity, course heading, time stamp, and the number of satellites that the BlackBerry device is tracking.

  1. Import the required classes.
    import javax.microedition.location.*;
  2. Create a class and a constructor.
    public class handleGPS
    {
        public handleGPS()
        {
        }
    }
  3. In the class, declare static fields for a thread and for each item of location information that you retrieve.
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;
    static float  heading;
    static float  velocity;
    static long   timeStamp;
    static String nmeaString;
  4. In the constructor, create and start a thread.
    gpsThread = new GPSThread();
    gpsThread.start();
  5. In the class, create a private static class that extends Thread, and create a run() method.
    private static class GPSThread extends Thread
    {
       public void run()
       {
       }
    }
  6. In run(), create an instance of the Criteria class. Invoke setCostAllowed(false) to specify the autonomous mode.
    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
  7. In run(), create a try/catch block. In this block create an instance of the LocationProvider class by getting an instance of the Criteria object. Create a try/catch block within this block, and create an instance of the Location class to retrieve the current GPS fix including a 300 second timeout expiry. Populate the fields, and specify the number of satellites by invoking getExtraInfo("application/X-jsr179-location-nmea").
    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 )
       {}
       catch ( LocationException lex )
       {}
    }
    catch ( LocationException lex )
    {}
    
    return;
Back To Top

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;
        }
    }
}
Back To Top

Retrieving location information by using the BlackBerryLocation class

You can use the BlackBerry extensions to JSR 179 to retrieve location information about the BlackBerry device. You can use the BlackBerryLocation class to retrieve the following information:

  • number of satellites that a BlackBerry device is tracking
  • details about the satellites that a BlackBerry device is tracking
  • average signal quality of a satellite
  • data source that produces the GPS fix (an internal or an external GPS receiver)
  • GPS mode that provides the location information
Back To Top

Retrieve satellite information by using the BlackBerryLocation class

You can request a GPS fix and then retrieve the current number of satellites in view, tracked satellites, average satellite signal quality, GPS data source (internal or external GPS), and the GPS mode.

  1. Import the required classes.
    import java.util.*;
    import java.lang.*;
    import net.rim.device.api.gps.*;
  2. Create a class and a constructor.
    public class handleGPS
    {
       public handleGPS()
       {
       }
    }
  3. In the class, declare static fields for a thread and for each item of location information that you retrieve.
    static GPSThread gpsThread;
    static int satCount;
    static int signalQuality;
    static int dataSource;
    static int gpsMode;
  4. In the constructor, create and start a thread.
    gpsThread = new GPSThread();
    gpsThread.start();
  5. In the class, create a private static class that extends Thread and a run() method.
    private static class GPSThread extends Thread
    {
        public void run()
        {
        }
    }
  6. In run(), create a try/catch block. In this block, create an instance of the BlackBerryCriteria class that specifies the GPS mode. Create a second try/catch block. In this block create an instance of the BlackBerryLocationProvider class by getting an instance of the BlackBerryCriteria object.
    try
    {
        BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);
    
        try
        {
            BlackBerryLocationProvider myProvider =
                (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
    
  7. Create a third try/catch block that is in the first try/catch block. Create a BlackBerryLocation object to retrieve the GPS fix including a 300 second timeout expiry. Populate the fields and extract the satellite information into a StringBuffer object.
    try
    {
        BlackBerryLocation myLocation =
            (BlackBerryLocation)myProvider.getLocation(300);
                        
        satCount= myLocation.getSatelliteCount();
        signalQuality = myLocation.getAverageSatelliteSignalQuality();
        dataSource = myLocation.getDataSource();
        gpsMode = myLocation.getGPSMode();
    
        SatelliteInfo si;
        StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n");
        String separator = ":";
    
        for (Enumeration e = myLocation.getSatelliteInfo();
            e!=null && e.hasMoreElements(); )
        {
            si = (SatelliteInfo)e.nextElement();
            sb.append(si.getId() + separator);
            sb.append(si.getSignalQuality() + separator);
            sb.append(si.getElevation() + separator);
            sb.append(si.getAzimuth());
            sb.append('\n');
        }
    }
    catch ( InterruptedException iex )
    {}
    catch ( LocationException lex )
    {}
Back To Top

Code sample: Using the BlackBerryLocation class to retrieve satellite information

import net.rim.device.api.gps.*;
import java.util.*;
import javax.microedition.location.*;

public class handleGPS
{
    static GPSThread gpsThread;
    static int satCount;
    static int signalQuality;
    static int dataSource;
    static int gpsMode;

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

    private static class GPSThread extends Thread
    {
        public void run()
        {
            try
            {
                BlackBerryCriteria myCriteria =
                  new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);

                try
                {
                    BlackBerryLocationProvider myProvider =
                      (BlackBerryLocationProvider)
                        LocationProvider.getInstance(myCriteria);

                    try
                    {
                        BlackBerryLocation myLocation =
                          (BlackBerryLocation)myProvider.getLocation(300);

                        satCount= myLocation.getSatelliteCount();
                        signalQuality =
                          myLocation.getAverageSatelliteSignalQuality();
                        dataSource = myLocation.getDataSource();
                        gpsMode = myLocation.getGPSMode();

                        SatelliteInfo si;
                        StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n");
                        String separator = ":";

                        for (Enumeration e = myLocation.getSatelliteInfo();
                          e!=null && e.hasMoreElements(); )
                        {
                            si = (SatelliteInfo)e.nextElement();
                            sb.append(si.getId() + separator);
                            sb.append(si.getSignalQuality() + separator);
                            sb.append(si.getElevation() + separator);
                            sb.append(si.getAzimuth());
                            sb.append('\n');
                        }
                    }
                    catch ( InterruptedException iex )
                    {
                        return;
                    }
                    catch ( LocationException lex )
                    {
                        return;
                    }
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( UnsupportedOperationException uoex )
            {
                return;
            }

            return;
        }
    }
}
Back To Top

Change the criteria to receive location information

You can use an instance of the LocationProvider class to automatically change the criteria that is used to track the location of a BlackBerry device.

  1. Import the required classes and interface.
    import net.rim.device.api.gps.GPSInfo;
    import javax.microedition.location.*;
  2. Create a class and constructor.
    public class handleGPS
    {
       public handleGPS(int gpsMode)
       {
       }
    }
  3. In the class, define static fields for the location provider, latitude, longitude, altitude, speed and course.
    static LocationProvider locationProvider;
    static double lat, lon;
    static float  alt, spd, crs;
  4. In the constructor, add a code block to set up a LocationProvider instance to switch to a different method of location tracking. Invoke reset() on the LocationProvider object, and then set the location listener to null to disable the listener.
    if (locationProvider != null)
    {
        locationProvider.reset();
        locationProvider.setLocationListener(null, -1, -1, -1);
    }
  5. In the constructor, create and configure a Criteria object based on the GPS mode that is passed as a parameter to the constructor.
    Criteria myCriteria = new Criteria();
    myCriteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
    myCriteria.setCostAllowed(true);
    
    if ( gpsMode == GPSInfo.GPS_MODE_AUTONOMOUS )
    {
        myCriteria.setCostAllowed(false);
    }
    else if ( gpsMode == GPSInfo.GPS_MODE_ASSIST )
    {
        myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);
    }
    else
    {
        myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
    }
  6. In the constructor, create a try/catch block. In this block, create an instance of the LocationListener class by invoking getInstance() and passing the Criteria object as a parameter. Specify a location listener to handle the GPS location updates.
    try
    {
       locationProvider = LocationProvider.getInstance(myCriteria);
    
       if (locationProvider != null)
       {
          locationProvider.setLocationListener
            (new myLocationListener(), -1, -1, -1);
       }
    }
    catch (Exception err)
    {}
  7. In the class, create a private static class that implements the LocationListener interface. Retrieve the current location information in the locationUpdated() method. Create a basic implementation of the providerStateChanged() method to monitor the LocationProvider state.
    private static class myLocationListener implements LocationListener
    {
       public void locationUpdated(LocationProvider provider, Location location)
       {
          lat = location.getQualifiedCoordinates().getLatitude();
          lon = location.getQualifiedCoordinates().getLongitude();
          alt = location.getQualifiedCoordinates().getAltitude();
          spd = location.getSpeed();
          crs = location.getCourse();
       }
    
       public void providerStateChanged(LocationProvider provider, int newState)
       {}
    }
Back To Top

Code sample: Changing the criteria to retrieve location information

import net.rim.device.api.gps.GPSInfo;
import javax.microedition.location.*;

public class handleGPS
{
    static LocationProvider locationProvider;
    static double lat, lon;
    static float  alt, spd, crs;

    public static void main(String[] args)
    {
    }

    public handleGPS(int gpsMode)
    {
        if (locationProvider != null)
        {
            locationProvider.reset();
            locationProvider.setLocationListener(null, -1, -1, -1);
        }

        Criteria myCriteria = new Criteria();
        myCriteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
        myCriteria.setCostAllowed(true);

        if ( gpsMode == GPSInfo.GPS_MODE_AUTONOMOUS )
        {
            myCriteria.setCostAllowed(false);
        }
        else if ( gpsMode == GPSInfo.GPS_MODE_ASSIST )
        {
            myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);
        }
        else
        {
            myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
        }

        try
        {
            locationProvider = LocationProvider.getInstance(myCriteria);

            if (locationProvider != null)
            {
                locationProvider.setLocationListener
                    (new myLocationListener(), -1, -1, -1);
            }
        }
        catch (Exception err)
        {
        }
    }

    private static class myLocationListener implements LocationListener
    {
        public void locationUpdated(LocationProvider provider, Location location)
        {
            lat = location.getQualifiedCoordinates().getLatitude();
            lon = location.getQualifiedCoordinates().getLongitude();
            alt = location.getQualifiedCoordinates().getAltitude();
            spd = location.getSpeed();
            crs = location.getCourse();
        }

        public void providerStateChanged(LocationProvider provider, int newState)
        {
        }
    }
}
Back To Top
Next topic: Error handling

Was this information helpful? Send us your comments.