Sorry about the red box, but we really need you to update your browser. Read this excellent article if you're wondering why we are no longer supporting this browser version. Go to Browse Happy for browser suggestions and how to update.

Specifying the GPS mode

You must specify the GPS mode to retrieve the location of a BlackBerry device. GPS modes include autonomous, assisted, and cell site.

  • Autonomous mode relies on GPS satellites only.
  • Assisted mode relies on GPS satellites and servers on the wireless network.
  • Cell site mode relies on the geolocation service, or the wireless network to provide the location information of the current base station.

GPS modes

Your BlackBerry device application must verify that a GPS mode is available for use on each BlackBerry device that your application runs on, before your application can use the GPS mode.

GPS mode

Description

cell site

This mode uses the wireless network to achieve the first GPS fix, and is generally considered the fastest mode. This mode does not provide BlackBerry device tracking information such as the speed and the bearing.

autonomous

This mode uses the GPS receiver on the BlackBerry device to retrieve location information. This mode cannot be used indoors or in close proximity to many physical obstructions, and it can take several minutes to fully synchronize with four or more satellites for the first GPS fix.

assisted

This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast retrieval of the first GPS fix.

MS-based

This mode uses the wireless network to retrieve satellite information. After the first GPS fix, the BlackBerry device relies on the autonomous mode to more accurately retrieve subsequent GPS fixes. The MS-based GPS mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA network.

MS-assisted

This mode uses the wireless network to retrieve satellite information. This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA network.

speed optimal

This mode focuses on providing the fastest possible GPS fix that meets the criteria that is set by the application. This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA network.

accuracy optimal

This mode is determined based on the accuracy of a GPS fix. This mode either relies on network information, or performs local calculations, depending on which is the most accurate and available. This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA network.

data optimal

This mode is determined based on the least amount of network traffic that is required for a GPS fix. This mode either relies on network information, or performs local calculations, depending on what is available that uses the least amount of data traffic. This mode applies to BlackBerry devices that use the Qualcomm gpsOne and operate on the CDMA network.

Bluetooth enabled GPS

This mode is determined by the configuration of the Bluetooth enabled GPS device. The configuration of a Bluetooth enabled GPS device that is paired with a BlackBerry device cannot be specified in a Criteria object.

Specifying the GPS mode with JSR 179

If you use the JSR 179 package, you must specify the properties for the GPS mode in the javax.microedition.location.Criteria class. The application cannot set the GPS mode directly. If a BlackBerry device is paired with a Bluetooth enabled GPS device to determine location, then the Bluetooth enabled device will be used regardless of how the Criteria object has been configured.

Specifying the GPS mode (JSR 179)

The JSR 179 Location API is supported on BlackBerry devices that run BlackBerry Device Software 4.0.2 or later.

Import the required class.

import javax.microedition.location.Criteria;

Create a class and constructor.

public class handleGPS
{
    public handleGPS()
    {
    }
}

In the constructor, create an instance of the Criteria class. Create a variable to specify a GPS mode.

Criteria myCriteria = new Criteria();
int myMode = 2; // AUTONOMOUS

In the constructor, map the properties for each GPS mode by invoking the corresponding set method for each property.

switch ( myMode )
{
    case 0: // CELLSITE
        myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
        myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
        myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
        myCriteria.setCostAllowed(true);
        break;

    case 1: // ASSIST
        myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);
        myCriteria.setHorizontalAccuracy(100);
        myCriteria.setVerticalAccuracy(100);
        myCriteria.setCostAllowed(true);
        break;

    case 2: // AUTONOMOUS
        myCriteria.setCostAllowed(false);
        break;
}

Criteria mapping properties

If you use the JSR 179 Location API to specify a GPS mode, you must map the following properties for the Criteria class.

GPS mode

Horizontal accuracy

Vertical accuracy

Cost allowed

Power usage level

Response time

Fix frequency

Autonomous

required

required

no

any

any

single or multiple

Autonomous

not required

not required

no

medium, high, or not required

any

single or multiple

Assisted or data optimal

not required

not required

yes

medium, high, or not required

any

single or multiple

Assisted or speed optimal

required

required

yes

high

quality of service

multiple

Assisted or MS-Based

required

required

yes

medium or not required

quality of service

multiple

Assisted or accuracy optimal

required

required

yes

high

quality of service

single

Assisted or MS-Assisted

required

required

yes

medium or not required

quality of service

single

Cell site

not required

not required

yes

low

any

any

Specifying the GPS mode by using BlackBerry extensions to JSR 179

The BlackBerry extensions to JSR 179 provide an enhanced set of GPS criteria. The net.rim.device.api.gps.BlackBerryCriteria class extends the javax.microedition.location.Criteria class. You can use the methods in the BlackBerryCriteria class to specify the GPS requirements for your application.

Method

Description

setMode (int)

You can use this method to specify an initial GPS mode when you create a BlackBerryCriteria object.

setFailoverMode (int, int, int)

You can use this method to specify a GPS failover mode to use when the initial GPS mode is unsuccessful. This method applies only to the internal GPS functionality on a BlackBerry device.

setSubsequentMode (int)

You can use this method to specify a subsequent GPS mode to use after a successful first GPS fix is retrieved.

setGPSRestartInterval (int, int)

You can use this method to specify an interval to wait before automatically restarting the GPS retrieval process when a GPS fix is not successfully retrieved. You can specify intervals to a maximum of 15 minutes and a minimum of 2 seconds, with a limit of three automatic retries.

setSatelliteInfoRequired (boolean, boolean)

You can use this method to specify whether you want satellite tracking information. The satellite tracking information consists of the number of satellites in view, and their IDs, signal quality, elevation, and azimuth. This applies only to the internal GPS functionality on a BlackBerry device.

Specifying the GPS mode with BlackBerry extensions to JSR 179

The BlackBerry extensions to JSR 179 are supported on BlackBerry devices that run BlackBerry Device Software 5.0.0 or later.

Import the required class.

import net.rim.device.api.gps.*;

Create a class and constructor.

public class handleGPS
{
    BlackBerryCriteria myCriteria;

    public handleGPS()
    {
    }
}

In the constructor, create a try/catch block. In this block, create an instance of the BlackBerryCriteria class by passing the GPS mode as a parameter to the constructor.

try
{
    myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);
}
catch ( UnsupportedOperationException ex )
{
    return;
}

In the constructor, invoke setFailloverMode() to specify the GPS failover mode to use if the first GPS mode that you specify cannot retrieve a GPS fix. Invoke setSubsequentMode() to specify a subsequent GPS mode to use after a successful first fix is retrieved.

myCriteria.setFailoverMode(GPSInfo.GPS_MODE_AUTONOMOUS, 3, 100);
myCriteria.setSubsequentMode(GPSInfo.GPS_MODE_AUTONOMOUS);

To verify if a GPS mode is supported, invoke GPSInfo.isGPSModeAvailable() and pass the GPS mode as a parameter. Invoke setMode() to specify the GPS mode, if the mode is supported.

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

        if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST))
            myCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
        else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
            myCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
    }
}

Retrieving location information with the assisted GPS mode

Assisted mode using a PDE server

The assisted mode can be used with BlackBerry devices that are associated with a CDMA network that utilizes PDE server technology. The assisted mode is designed to provide fast retrieval of a GPS fix.

Assisted GPS capabilities are currently defined by wireless service providers. In many instances, you must enter into a formal relationship with wireless service providers before you can connect to their PDE server.

Verify that PDE server information is required

Before using assisted mode with a PDE server, you must verify whether PDE server information is required.

Import the required class.

import net.rim.device.api.gps.GPSSettings;

Create a class and constructor. In the constructor, invoke isPDEInfoRequired() to verify if you need to specify the PDE server information to use assisted mode.

public class checkPDE
{
   public checkPDE()
   {
      if ( isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST))
      {
          // set up PDE server access
      }
   }
}

Code sample: Specifying the PDE server information

You must have the user ID, password, IP address and port number that the wireless service provider uses for their PDE server.

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

public class handleGPS
{
    static  GPSThread gpsThread;

//Create a class and a constructor. 
    public handleGPS()
    {

//In the constructor, create and start an instance of the Thread class. 
        gpsThread = new GPSThread();
        gpsThread.start();
    }

//In the class, create a class that extends Thread. 
    private static class GPSThread extends Thread
    {
        public void run()
        {

//In the run() method of the private class, invoke isGPSModeAvailable() 
//passing GPS_MODE_ASSIST as a parameter to determine if the assisted 
//mode is available on the BlackBerry device. Invoke isPDEInfoRequired()
//to determine if you need to specify PDE server information. 
//If PDE server information is required, create an instance of 
//the BlackBerryCriteria class by passing GPS_MODE_ASSIST as a 
//parameter to the constructor.  
            if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) ||
                !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST))
                return;

            BlackBerryCriteria myCriteria =
                new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

//In the run method of the private class, create a try/catch block. 
//In the block, associate an instance of the BlackBerryCriteria class with a 
//BlackBerryLocationProvider object. Create and specify the user ID, 
//password, and IP address String objects, and the port ID. 
//Combine the String objects into a single String. Invoke setPDEInfo()
//to specify the PDE server IP address and port of the BlackBerry device. 
            try
            {
                BlackBerryLocationProvider myProvider = 
                  (BlackBerryLocationProvider)
                  LocationProvider.getInstance(myCriteria);
                String user = "UserID";
                String pass = "Password";
                String ip = "127.0.0.1";
                int port = 0;
                String str = ip + ";" + user + ";" + pass;
                GPSSettings.setPDEInfo(str, port);

                try
                {
                    BlackBerryLocation myLocation =
                      (BlackBerryLocation)myProvider.getLocation(10);
                }
                catch ( InterruptedException iex )
                {
                    return;
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( LocationException lex )
            {
                return;
            }
            return;
        }
    }
}

Retrieving a location provider

After you specify the GPS mode, you must retrieve the location provider that your application uses to support the GPS mode. A location provider represents the source of the location information and it works based on given criteria (for example, the horizontal accuracy and the power usage) .

If the application uses the Criteria class from the JSR 179 package to specify a GPS mode, then the application must retrieve an instance of the LocationProvider class. If the application uses the BlackBerryCriteria class, then the application must retrieve an instance of the BlackBerryLocationProvider class.

A BlackBerryLocationProvider object extends the javax.microedition.location.LocationProvider class. You can use BlackBerryLocationProvider to perform the following actions:

  • Process a location request that you specify in the net.rim.device.api.gps.BlackBerryCriteria object.
  • Pause and resume the location listener.
  • Retrieve the GPS receiver type including an internal or a Bluetooth-enabled GPS receiver.

When the location listener is in a paused state, the application does not receive GPS fixes. The location listener can be in a ready state while also in a paused state.

Code sample: Retrieving a location provider by using the LocationProvider class

import javax.microedition.location.*;

//Create a class and a constructor. 
public class handleGPS
{
    public handleGPS()
    {

//In the constructor, create an instance of the Criteria class. 
        Criteria myCriteria = new Criteria();

//In the constructor, configure the Criteria object to use the specified GPS mode. 
//In the following code sample, autonomous mode is specified by invoking 
//setCostAllowed(false). 
        int myMode = 2; // AUTONOMOUS

        switch ( myMode )
        {
            case 0: // CELLSITE
                myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
                myCriteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
                myCriteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
                myCriteria.setCostAllowed(true);
                break;

            case 1: // ASSIST
                myCriteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_MEDIUM);
                myCriteria.setHorizontalAccuracy(100);
                myCriteria.setVerticalAccuracy(100);
                myCriteria.setCostAllowed(true);
                break;

            case 2: // AUTONOMOUS
                myCriteria.setCostAllowed(false);
                break;
        }

//In the constructor, create a try/catch block. Within the block, create a 
//LocationProvider object by invoking getInstance()
        try
        {
            LocationProvider myProvider = LocationProvider.getInstance(myCriteria);
        }
        catch ( LocationException lex )
        {
            return;
        }
    }
}

Controlling location tracking by using the BlackBerryLocationProvider class

The net.rim.device.api.gps.BlackBerryLocationProvider class extends the javax.microedition.location.LocationProvider class and it is required for BlackBerry device applications that use the BlackBerry extensions to JSR 179. You can use the methods that are provided in the BlackBerryLocationProvider class to control location tracking.

Method

Description

getProviderType()

This method retrieves the source of the location information. The source is either an internal or external GPS receiver.

pauseLocationTracking (int interval)

This method pauses location tracking and stops receiving GPS fixes. You can pass an interval parameter, specified in seconds, to make sure that the GPS receiver remains active during the pause interval. You can pass an interval of 0 to indefinitely stop location tracking and make the GPS receiver inactive.

resumeLocationTracking()

This method resumes location tracking after it is in a paused state.

stopLocationTracking()

This method stops location tracking only if tracking was previously started. Your application must invoke BlackBerryLocationProvider.reset() before it restarts location tracking by using the same location provider.

Code sample: Using the BlackBerryLocationProvider class to control location tracking

You can pause, resume, and stop location tracking by using the net.rim.device.api.gps.BlackBerryLocationProvider class.

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

//Create a new class and a constructor. 
public class handleGPS
{
    static BlackBerryLocationProvider myProvider;

    public handleGPS()
    {

//In the constructor, create a try/catch block. In the block, create 
//an instance of the BlackBerryCriteria class by passing the GPS mode 
//as a parameter to the constructor. 
        try
        {
            BlackBerryCriteria myCriteria =
              new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);

//In the try part of the block, create a new try/catch block. In this 
//block, create an instance of the BlackBerryLocationProvider class by 
//retrieving an instance of the BlackBerryCriteria class. Invoke 
//setLocationListener() by passing the interval value, timeout value, and 
//maximum age as parameters to add a LocationListener.
            try
            {
                myProvider = (BlackBerryLocationProvider)
                  LocationProvider.getInstance(myCriteria);
                myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1);
            }
            catch ( LocationException lex )
            {
                return;
            }

//Outside of the try/catch block, invoke pauseLocationTracking(), 
//resumeLocationTracking(), or stopLocationTracking() to pause, 
//resume, or stop location tracking.  
            myProvider.pauseLocationTracking(30);
            myProvider.resumeLocationTracking();
            myProvider.stopLocationTracking();
        }
        catch ( UnsupportedOperationException uoex )
        {
            return;
        }

        return;
    }

//In the class, implement the LocationListener interface. Implement the 
//basic framework for the locationUpdated() method, and the 
//providerStateChanged() method. 
    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.AVAILABLE)
            {
                // available
            }
            else if (newState == LocationProvider.OUT_OF_SERVICE)
            {
                // GPS unavailable due to IT policy specification
            }
            else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE )
            {
                // no GPS fix
            }
        }
    }
}

Retrieve a location provider by using the BlackBerryLocationProvider class

Import the required classes.

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

Create a class and a constructor.

public class handleGPS
{
    static BlackBerryCriteria myCriteria;

    public handleGPS()
    {
    }
}

In the constructor, create a try/catch block. In the block, create an instance of the BlackBerryCriteria class and pass the GPS mode to the constructor. Create a second try/catch block, then create an instance of the BlackBerryLocationProvider class by invoking getInstance() to retrieve an instance of the BlackBerryCriteria object.

        try
        {
            myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

            try
            {
                BlackBerryLocationProvider myProvider =
                  (BlackBerryLocationProvider)
                    LocationProvider.getInstance(myCriteria);
            }
            catch ( LocationException lex )
            {
                return;
            }
        }
        catch ( UnsupportedOperationException ex )
        {
            return;
        }
    }
}

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.

Code sample: Retrieving the GPS location of a BlackBerry device

import javax.microedition.location.*;

//Create a class and a constructor. 
public class handleGPS
{

//Declare static fields in the class. 
    static GPSThread gpsThread;
    static double latitude;
    static double longitude;

    public handleGPS()
    {

//In the constructor, create and start a local thread. 
        gpsThread = new GPSThread();
        gpsThread.start();
    }


//In the class, create a private class that extends Thread, 
//and create a run() method. 
    private static class GPSThread extends Thread
    {
        public void run()
        {

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

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

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

You can use the Location API to retrieve location information of a BlackBerry device at any interval.

import javax.microedition.location.*;

//Create a class and a constructor. 
public class handleGPS
{
    public handleGPS()
    {

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

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

Retrieving location information with 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

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

import javax.microedition.location.*;

//Create a class and a constructor.
public class handleGPS
{

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

    public handleGPS()
    {

//In the constructor, create and start a thread. 
        gpsThread = new GPSThread();
        gpsThread.start();
    }

//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()
        {

//In run(), create an instance of the Criteria class. Invoke 
//setCostAllowed(false) to specify the autonomous mode. 
            Criteria myCriteria = new Criteria();
            myCriteria.setCostAllowed(false);

//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 )
                {
                    return;
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( LocationException lex )
            {
                return;
            }

            return;
        }
    }
}

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

Code sample: Using the BlackBerryLocation class to retrieve satellite information

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.

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

//Create a class and a constructor. 
public class handleGPS
{

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

    public handleGPS()
    {

//In the constructor, create and start a thread. 
        gpsThread = new GPSThread();
        gpsThread.start();
    }

//In the class, create a private static class that extends 
//Thread and a run() method. 
    private static class GPSThread extends Thread
    {
        public void run()
        {

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

//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 )
                    {
                        return;
                    }
                    catch ( LocationException lex )
                    {
                        return;
                    }
                }
                catch ( LocationException lex )
                {
                    return;
                }
            }
            catch ( UnsupportedOperationException uoex )
            {
                return;
            }

            return;
        }
    }
}

Code sample: Changing the criteria to retrieve 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.

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

//Create a class and constructor. 
public class handleGPS
{

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

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

    public handleGPS(int gpsMode)
    {

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

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

//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)
        {
        }
    }

//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)
        {
        }
    }
}

Error handling

You can retrieve the last error that was received when a GPS fix is unsuccessful by invoking GPSInfo.getLastGPSError() (available in the JSR 179 Location API) or BlackBerryLocation.getError() (available in the BlackBerry extensions to JSR 179).

Handle errors (JSR 179)

If a request for a GPS fix is unsuccessful, you can retrieve the last returned error.

Import the required class.

import net.rim.device.api.gps.GPSInfo;

Create a class and a constructor.

public class handleGPS
{
    public handleGPS()
    {
    }
}

In the constructor, invoke GPSInfo.getLastGPSError() to retrieve the error.

switch (GPSInfo.getLastGPSError())
{
    case GPSInfo.GPS_ERROR_NONE: break;
    case GPSInfo.GPS_ERROR_ALMANAC_OUTDATED: break;
    case GPSInfo.GPS_ERROR_AUTHENTICATION_FAILURE: break;
    case GPSInfo.GPS_ERROR_CHIPSET_DEAD: break;
    case GPSInfo.GPS_ERROR_DEGRADED_FIX_IN_ALLOTTED_TIME: break;
    case GPSInfo.GPS_ERROR_GPS_LOCKED: break;
    case GPSInfo.GPS_ERROR_INVALID_NETWORK_CREDENTIAL: break;
    case GPSInfo.GPS_ERROR_INVALID_REQUEST: break;
    case GPSInfo.GPS_ERROR_LOW_BATTERY: break;
    case GPSInfo.GPS_ERROR_NETWORK_CONNECTION_FAILURE: break;
    case GPSInfo.GPS_ERROR_NO_FIX_IN_ALLOTTED_TIME: break;
    case GPSInfo.GPS_ERROR_NO_SATELLITE_IN_VIEW: break;
    case GPSInfo.GPS_ERROR_PRIVACY_ACCESS_DENIED: break;
    case GPSInfo.GPS_ERROR_SERVICE_UNAVAILABLE: break;
    case GPSInfo.GPS_ERROR_TIMEOUT_DEGRADED_FIX_NO_ASSIST_DATA: break;
    case GPSInfo.GPS_ERROR_TIMEOUT_NO_FIX_NO_ASSIST_DATA: break;
}

Handle errors (BlackBerry extensions to JSR 179)

You can check the status of a GPS fix request by invoking the getStatus() method that is provided in the BlackBerry extensions to JSR 179. If the return is BlackBerryLocation.GPS_ERROR, you can retrieve the error value by invoking BlackBerryLocation.getError().

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

//Create a class and a constructor. 
public class handleGPS
{
    public handleGPS()
    {

//In the constructor, create a try/catch block. In this block, create an 
//instance of the BlackBerryCriteria class by passing the 
//GPS mode to the constructor. 
        try
        {
            BlackBerryCriteria myCriteria =
              new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);

//In the try/catch block, create another try/catch block. In this block, 
//create an instance of the BlackBerryLocationProvider class by retrieving the 
//BlackBerryCriteria object. Invoke setLocationListener() to specify 
//the location listener. 
            try
            {
                BlackBerryLocationProvider myProvider =
                  (BlackBerryLocationProvider)
                    LocationProvider.getInstance(myCriteria);
                myProvider.setLocationListener
                  (new myLocationListener(), -1, -1, -1);
            }
            catch ( LocationException lex )
            {
                return;
            }
        }
        catch ( UnsupportedOperationException ex )
        {
            return;
        }
    }

//In the class, create a static class that implements LocationListener. 
//Implement locationUpdated() and providerStateChanged(). 
    private static class myLocationListener implements LocationListener
    {
        public void locationUpdated
          (LocationProvider provider, Location location)
        {

//In locationUpdated(), verify if the location parameter is an instance 
//of BlackBerryLocation. If so, then create a local BlackBerryLocation 
//object by passing the location parameter. Invoke getStatus() to retrieve 
//the status of GPS location request, and then process the returned status. 
            if (location instanceof BlackBerryLocation)
            {
                BlackBerryLocation bLoc = (BlackBerryLocation)location;

                switch(bLoc.getStatus())
                {
                    case BlackBerryLocation.GPS_ERROR:
                        int gpsStatus = bLoc.getError();
                        break;

                    case BlackBerryLocation.FAILOVER_MODE_ON:
                    case BlackBerryLocation.SUBSEQUENT_MODE_ON:
                    case BlackBerryLocation.GPS_FIX_PARTIAL:
                    case BlackBerryLocation.GPS_FIX_COMPLETE:
                        break;
                }
            }
        }

        public void providerStateChanged
          (LocationProvider provider, int newState)
        {
        }
    }
}

Retrieving a GPS location by using a web page

You can use JavaScript to configure the GPS mode, and determine the current location of the BlackBerry device by using the BlackBerry Browser.

You can use the following JavaScript properties and methods to access the Location API from the BlackBerry Browser.

JavaScript property

Description

blackberry .location .GPSSupported

This property returns true when GPS is supported by the BlackBerry device.

blackberry .location .latitude

This property returns the current latitude, in degrees, of the BlackBerry device. Positive values indicate northern latitude, negative values indicate southern latitude.

blackberry .location .longitude

This property returns the current longitude, in degrees, of the BlackBerry device. Positive values indicate eastern longitude, negative values indicate western longitude

blackberry .location .timestamp

This property returns time (in milliseconds since epoch) at which the blackberry .location object was updated.

JavaScript method

Description

blackberry .location .setAidMode (mode)

This method specifies which GPS mode the BlackBerry device will use to determine the GPS location. The mode can be any one of the following values:

  • 0 for Cell Site mode
  • 1 for Assisted mode
  • 2 for Autonomous mode

blackberry .location .refreshLocation ()

This method requests an update of the location of the BlackBerry device. This method is asynchronous, so the script continues regardless of whether updated location information has been received. To ensure that location information is updated before reading it, you should first register a listener using blackberry .location .onLocationUpdate() that reads blackberry .location .latitude and blackberry .location .longitude, and then call refreshLocation() afterwards.

blackberry .location .onLocationUpdate ("callback")

This method registers a listener that evaluates a string or calls a function whenever the BlackBerry device receives updated location information.

On BlackBerry devices running versions of BlackBerry Device Software earlier than version 4.6, this function must be passed as a string that is evaluated each time the location is refreshed. On BlackBerry devices running BlackBerry Device Software version 4.6 or later, you can pass a string, or use the method to register a callback function.

Once onlocationUpdate() has been invoked, the callback occurs whenever there is an update to the location information.

This can be as frequent as once every several seconds. If you have passed the method a function, you can cancel the callback using blackberry.location.removeLocationUpdate(). If you have passed a string, the callback cannot be removed.

blackberry .location .removeLocationUpdate ()

This method removes a previously registered callback function. This method is only supported on BlackBerry devices running BlackBerry Device Software version 4.6 or later.

Retrieve a GPS location by using a web page

The following code sample demonstrates how to determine if a web page was loaded by the BlackBerry Browser and if the BlackBerry device supports GPS functionality. If these conditions are true, the web page receives the updated location information to start location tracking.

<!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>GPS Testing</title>
    </head>
    <body>
        <script type="text/javascript">
var modeCellsite   = 0;
var modeAssisted   = 1;
var modeAutonomous = 2;

function locationChanged()
{
    alert("Lat " + blackberry.location.latitude +
        " Lon " + blackberry.location.longitude +
        " Time " + blackberry.location.timestamp );
    return true;
}

if ( window.blackberry && blackberry.location.GPSSupported )
{
    var isUpdated = false;
    var theCount = 0;

    alert("Location tracking is supported");

    blackberry.location.onLocationUpdate("locationChanged()");
    blackberry.location.setAidMode(modeAutonomous);

    while ( theCount++ < 10 && !isUpdated )
        isUpdated = blackberry.location.refreshLocation();
}
else
{
    document.write("Location tracking is not supported");
}
        </script>
    </body>
</html>