MOTODEV // TECHNICAL ARTICLES
Welcome to MOTODEV // Please log in.

Introduction to the Java ME Location API

Imagine using location data in real-time to remember your favorite new restaurant or perfect fishing spot so you can make it back there again. Current mobile devices can provide this functionality for you, making the common handset the perfect co-pilot. This article outlines location technologies and the usage of Java ME location APIs which help developers easily build and implement compelling location applications.

Location Technologies

Location information can be expressed in spatial terms. A spatial location is expressed in the latitude-longitude-altitude coordinate system. Latitude is expressed as 0-90 degrees north or south of the equator, and longitude is 0-180 degrees east or west of the prime meridian, which passes through Greenwich, England. Altitude is expressed in meters above sea level.

There are several methods to determine the location of a mobile device. These methods may be handset-dependent or network-dependent. So you should know your handset and ask your carrier about the location method that works with your particular handset. Mobile location methods include both network based and mobile device based locations.

  1. Network based location
    • Cell-ID method. This method identifies the location of the handset by the Base Transceiver Station (BTS) that the handset is communicating with and the location of that BTS. The handset can be at any position in the cell. The precision is decided by the size of the cell, and it can be quite inaccurate.
    • E-OTD (Enhanced-Observed Time Difference)/U-TDOA (Uplink Time Difference of Arrival)/OTDOA (Observed Time Difference of Arrival) method etc. These methods use the time difference to locate the mobile device; the precision depends on the precision for the system time of the mobile network.
  2. Mobile device based location. GPS (Global Positioning System) is potentially the most accurate method, but it has some drawbacks: It consumes a lot of battery power while in use. It also suffers from canyon environments, such as in cities where satellite visibility is intermittent and the GPS signals are blocked by buildings and there are not enough satellites signals to estimate the positions of the user.
    • A-GPS (Assisted Global Positioning Systems). The mobile device must be equipped with a GPS receiver. The network uses the cell that the mobile device communicates with to locate the GPS satellite above the cell, and provides this information to the mobile device. The mobile device uses such information to narrow down the searching scope and shorten the searching time so that it can locate the satellite more quickly.
    • Autonomous GPS. The mobile device has a full function GPS receiver. The location information is obtained by the mobile device itself. It may, however, take some time to get an initial fix on the visible satellites.

Table1: Comparison of location methods

Location method Calculation Device/network modification Expense* Location area Accuracy (meters)
GPS A-GPS: both the network and the mobile device are needed to do the calculation Both the network and the mobile device need to be modified Medium Limited in canyon environments 5-40
Autonomous GPS: the mobile device does the calculation Only the mobile device needs to be modified
Network Network Cell-ID: no changes needed Low Limited to within the cell 100-30000
E-OTD: both the network and the mobile device need to be modified Medium Limited to within the country 50-400
U-TDOA /OTDOA: the network needs to be modified High Limited to within the country 50-200
Note

NOTE:* The expense is for modifications to enable location support. These costs could to the developer and/or to the network operator who wants to provide location support.

For the handset-independent location method, there are different mobile devices on the market that you can use.

  • Use handsets which have a built-in GPS chipset in them. The handset must support the Location API JSR-179. In this case, you can use the Location API. This article will discuss this method and the Location APIs more in the following section.
  • For handsets which have no built-in GPS chipset, you can use a serial or Bluetooth connection with a GPS module. This article does not discuss this case. Please refer to the “Introduction to GPS” article which is listed in the References section at the end of this article.

Developing Applications using Location API

It is up to the developer to decide how to implement a location application. Here are some choices that you can use.

  • Using Client/Server mode, the server does most of the processing logics and responds to the handset client with the requested map images. The handset client only accepts the user input and sends the request to the server. This method has the disadvantage of longer response time and slower speed. You may also have to pay extra fees for a network connection to your server.
  • Storing map images and their data on the handset: this method has the advantage of higher response speed. However, it requires the handset client to have more capacity which includes storage, processing ability, battery life, etc.

Table 2: JSR-179 main classes

Class Description Usage notes
LocationProvider Represents a source of the location information, starting point of location request.  
Criteria Used for the selection of the location provider.  
Location Represents the standard set of basic location information. This includes the time-stamped coordinates, accuracy, speed, course, etc. The implementation has a limit for the maximum number of location read requests that can be sent simultaneously.
Coordinates Represents coordinates as latitude-longitude-altitude values.  
LocationListener Listener that receives update events associated with a particular LocationProvider.  
ProximityListener Receives updates based on terminal crossing into a defined radius around a coordinate. The implementation has a limit for the maximum number of proximity listeners that can be added simultaneously.
Landmark The Landmark class represents a landmark, such as a known location with a name (such as a monument). The implementation has limitations such as maximum number of landmark store categories, landmarks in landmark store, etc.
LandmarkStore The LandmarkStore class provides methods to store, delete and retrieve landmarks from a persistent landmark store. The implementation may only support default landmark store and not support creating and deleting LandmarkStore methods.

The Location API for J2ME (JSR-179) provides a standard interface to access location based information. The classes are in the optional package javax.microedition.location. The three main features of the Location API are:

  • Obtaining information about the location of a device
  • The possibility to create, edit, store, and retrieve landmarks
  • The possibility to obtain the orientation of a device.(The implementation of the device may not support this feature.)

Table 2, shown previously, gives the main classes and their brief description.

The following is a code snippet using the Location API. The developer can refer to the JSR-179 specification for detailed usage.

......
try {
    Criteria crit = new Criteria();
    crit.setCostAllowed(true); //default value
    crit.setSpeedAndCourseRequired(true);
    crit.setHorizontalAccuracy(500);
    crit.setAltitudeRequired(true);
    crit.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
    // Instantiate a location provider with specified criteria
    LocationProvider locp = LocationProvider.getInstance(crit);
    // Get a location fix for 30 seconds timeout
    Location loc = locp.getLocation(30);
} catch (LocationException e) {
    // location unavailable
    System.out.println(e.toString());
}
......
    if (loc.isValid()) {
        float course = loc.getCourse();
        float speed = loc.getSpeed();
        Coordinates qc = loc.getQualifiedCoordinates();
        if (qc!=null) {
            double latitude = qc.getLatitude();
            double longitude = qc.getLongitude();
            float altitude = qc.getAltitude();
        }
    }
    else
        System.out.println("location invalid");

	

The developer can set LocationListener to the LocationProvider using the method shown next.

LocationProvider.setLocationListener(LocationListener?listener, int interval, int timeout, int maxAge)

The developer can add a ProximityListener for updates when proximity to the specified coordinates is detected.

LocationProvider.addProximityListener(ProximityListener listener, Coordinates coordinates, float proximityRadius)

Here is an example of LocationListener and ProximityListener that can be used to get the location update of the LocationProvider and be invoked when the device enters the proximity of the registered coordinates.

//This class is the inner class of LocationDemoMIDlet class
class MyLocationListener implements LocationListener {
    public void locationUpdated(LocationProvider lp, Location location) {
        LocationDemoMIDlet.this.location = location;
        String s = "locationUpdated method invoked";
        Alert alert = new Alert("locationUpdated", s, null, null);
        alert.setTimeout(2000);
        LocationDemoMIDlet.this.display.setCurrent(alert);
    }
    public void providerStateChanged(LocationProvider lp, int i) {
       //Utility.getStateString gets the state string such as 1 stands for Available
        String s = "providerStateChanged = "+Utility.getStateString(i);
        Alert alert = new Alert("providerStateChanged", s, null, null);
        alert.setTimeout(2000);
        LocationDemoMIDlet.this.display.setCurrent(alert);
    }
}  
class MyProximityListener implements ProximityListener {
    public void proximityEvent(Coordinates coordinates, Location location){
        String s = "proximityEvent method invoked, entered the registered area";
        Alert alert = new Alert("proximityEvent", s, null, null);
        alert.setTimeout(2000);
        LocationDemoMIDlet.this.display.setCurrent(alert);
    }

    public void monitoringStateChanged(boolean flag){
        String s = "monitoringStateChanged invoked, isMonitoringActive = " + flag;
        Alert alert = new Alert("monitoringStateChanged", s, null, null);
        alert.setTimeout(2000);
        LocationDemoMIDlet.this.display.setCurrent(alert);
    }
}
LocationListener locationListener = new MyLocationListener();
ProximityListener proximityListener = new MyProximityListener();
locationProvider.setLocationListener(locationListener, 60, 10, 10);
LocationProvider.addProximityListener(proximityListener, coordinates, 200);
	

Next is an example of using LandmarkStore to get all the landmarks stored in it.

public void getLandmarksAll() {
     try {
         //Get the default landmark store
           LandmarkStore landmarkStore = LandmarkStore.getInstance(null);
         Enumeration enumeration = landmarkStore.getLandmarks();
         if(enumeration != null && enumeration.hasMoreElements()) {
             int i = 1;
             while(enumeration.hasMoreElements()) {
                 Landmark landmark1 = (Landmark)enumeration.nextElement();
                 System.out.println("Landmark" + i + " = "+landmark1.getName());
             }
         } else {
             System.out.println("There is no landmark in the landmark store");
         }
     }
     catch (Exception e) {
    	 System.out.println(e.toString());
     }
 }

	

Using Location API Notes

Please pay attention to the following notes when developing an application using location API.

  • Location API support - Check whether the handset supports the Location API. For JSR-179, the developer can use: System.getProperty("microedition.location.version"). It returns the string for the Location API version if it is supported; if it is not supported, the returned string will be null.
  • Privacy issues - Please note that the location information may be considered very sensitive, and there may be concerns about maintaining privacy. The developer should take this into account when developing a location application. Another important consideration is the time required to get a location fix. It may take between 5 and 30 seconds, or perhaps even longer, to get the location.
  • Security issue - In order to use the Location API JSR-179, the MIDlet needs to be signed as a trusted one. Please refer to the details of the MIDP2.0 security model: http://jcp.org/en/jsr/detail?id=118. Also, the developer should add MIDlet-Permissions: javax.microedition.location.Location to the JAD file. Please refer to the JSR-179 specifications to get the full permission list to use different APIs in JSR-179. For your convenience there is a permissions table included at the end if this article.
  • The developer can integrate the location API with other MIDP APIs, such as:
    • WMA (Wireless Messaging API), to add location information into the SMS indicating your location to the SMS receiver
    • Connection APIs, to communicate with servers
    • MMA (Mobile Media API), to hear a voice of with directions or give your location
    • PIM (Personal Information Management) API, to associate the location information to the contacts in the handsets

Summary

There are many choices to implement a location application. The Location API provides the ability to get the location information of the mobile device. The Location API JSR-179 is convenient to use and it is a good choice to implement a location application on the mobile phones which support Java ME.

References

  1. JSR179, Location API
  2. J2ME and Location-Based Services
  3. Introduction to GPS
  4. Real-Life Use of JSR 179: Location API for the J2ME Platform

Permissions used in JSR-179

Table 3: Permissions used in JSR-179

Permission name Methods protected by this permission
javax.microedition.location.Location LocationProvider.getLocation(), LocationProvider.setLocationListener(), LocationProvider.getLastKnownLocation()
javax.microedition.location.Orientation Orientation.getOrientation()
javax.microedition.location.ProximityListener LocationProvider.addProximityListener()
javax.microedition.location.LandmarkStore.read LandmarkStore.getInstance(), LandmarkStore.listLandmarkStores()
javax.microedition.location.LandmarkStore.write LandmarkStore.addLandmark(), LandmarkStore.deleteLandmark(), LandmarkStore.removeLandmarkFromCategory(), LandmarkStore.updateLandmark()
javax.microedition.location.LandmarkStore.category LandmarkStore.addCategory(), LandmarkStore.deleteCategory()
javax.microedition.location.LandmarkStore.management LandmarkStore.createLandmarkStore(), LandmarkStore.deleteLandmarkStore()
Back to Top
Was This Document Helpful?
Yes  No 

Additional Comments (Optional)