You are on page 1of 11

LOCATION API JSR-179

V 1.0

TECHNICAL ARTICLE
Copyright © 2008, Motorola, Inc. All rights reserved. This documentation may be printed and copied solely for use in developing
products for Motorola products. In addition, two (2) copies of this documentation may be made for archival and backup purposes.
Except for the foregoing, no part of this documentation may be reproduced or transmitted in any form or by any means or used to
make any derivative work (such as translation, transformation, or adaptation) without express written consent from Motorola, Inc.
Motorola reserves the right to make changes without notice to any products or services described herein. "Typical" parameters,
which may be provided in Motorola Data sheets and/or specifications, can and do vary in different applications and actual
performance may vary. Customer's technical experts will validate all "Typicals" for each customer application.
Motorola makes no warranty in regard to the products or services contained herein. Implied warranties, including without limitation,
the implied warranties of merchantability and fitness for a particular purpose, are given only if specifically required by applicable law.
Otherwise, they are specifically excluded.
No warranty is made as to coverage, availability, or grade of service provided by the products or services, whether through a service
provider or otherwise. No warranty is made that the software will meet your requirements or will work in combination with any
hardware or application software products provided by third parties, that the operation of the software products will be uninterrupted
or error free, or that all defects in the software products will be corrected.
In no event shall Motorola be liable, whether in contract or tort (including negligence), for any damages resulting from use of a
product or service described herein, or for any indirect, incidental, special or consequential damages of any kind, or loss of revenue
or profits, loss of business, loss of information or data, or other financial loss arising out of or in connection with the ability or inability
to use the Products, to the full extent these damages may be disclaimed by law.
Some states and other jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, or limitation on
the length of an implied warranty, therefore the above limitations or exclusions may not apply to you.
This warranty gives you specific legal rights, and you may also have other rights, which vary from jurisdiction to jurisdiction.
Motorola products or services are not designed, intended, or authorized for use as components in systems intended for surgical
implant into the body, or other applications intended to support or sustain life, or for any other application in which the failure of the
Motorola product or service could create a situation where personal injury or death may occur.
Should the buyer purchase or use Motorola products or services for any such unintended or unauthorized application, the buyer
shall release, indemnify and hold Motorola and its officers, employees, subsidiaries, affiliates, and distributors harmless against all
claims, costs, damages, and expenses, and reasonable attorney fees arising out of, directly or indirectly, any claim of personal injury
or death associated with such unintended or unauthorized use, even if such claim alleges that Motorola was negligent regarding the
designing or manufacturing of the product or service.
Motorola recommends that if you are not the author or creator of the graphics, video, or sound, you obtain sufficient license rights,
including the rights under all patents, trademarks, trade names, copyrights, and other third party proprietary rights.
If this documentation is provided on compact disc, the other software and documentation on the compact disc are subject to the
license agreement accompanying the compact disc.
Location API JSR-179
Version 1.0
April 2008
For the latest version of this document, visit http://developer.motorola.com

Motorola, Inc.
http://www.motorola.com
Contents
Introduction to the Java ME Location API .................................................................................................... 3
Location Technologies............................................................................................................. 3
Developing Applications using Location API.......................................................................... 4
Using Location API Notes ....................................................................................................... 8
Summary .................................................................................................................................. 9
References 10
Permissions used in JSR-179 ....................................................................................................................... 10

[Insert Document Type] Page 2


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.

[Insert Document Type] Page 3


Table1: Comparison of location methods

Location Calculation Device/network Expense* Location area Accuracy


method modification (meters)

GPS A-GPS: both the Both the network and the Medium Limited in canyon 5-40
network and the mobile device need to be environments
mobile device are modified
needed to do the
calculation

Autonomous GPS: Only the mobile device


the mobile device needs to be modified
does the calculation

Network Network Cell-ID: no changes needed Low Limited to within 100-30000


the cell

E-OTD: both the network Medium Limited to within 50-400


and the mobile device need the country
to be modified

U-TDOA /OTDOA: the High Limited to within 50-200


network needs to be the country
modified

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.

[Insert Document Type] Page 4


• 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 The implementation has a limit for
information. This includes the time-stamped the maximum number of location
coordinates, accuracy, speed, course, etc. 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 The implementation has a limit for
into a defined radius around a coordinate. the maximum number of proximity
listeners that can be added
simultaneously.

Landmark The Landmark class represents a landmark, The implementation has limitations
such as a known location with a name (such as such as maximum number of
a monument). landmark store categories,
landmarks in landmark store, etc.

LandmarkStore The LandmarkStore class provides methods to The implementation may only
store, delete and retrieve landmarks from a support default landmark store and
persistent landmark store. 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.

[Insert Document Type] Page 5


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)

[Insert Document Type] Page 6


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;

[Insert Document Type] Page 7


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.

[Insert Document Type] Page 8


• 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.

[Insert Document Type] Page 9


References
1. JSR179, Location API. http://www.jcp.org
2. J2ME and Location-Based Services
http://developers.sun.com/techtopics/mobility/apis/articles/location/
3. Introduction to GPS http://www-128.ibm.com/developerworks/wireless/edu/wi-dw-wigps-i.html
4. Real-Life Use of JSR 179: Location API for the J2ME Platform
http://developers.sun.com/learning/javaoneonline/2005/mobility/TS-3242.pdf

Permissions used in JSR-179


Permission name Methods protected by this permission

LocationProvider.getLocation(),
javax.microedition.location.Location 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()

LandmarkStore.addLandmark(), LandmarkStore.deleteLandmark(),
javax.microedition.location.LandmarkStore.write LandmarkStore.removeLandmarkFromCategory(),
LandmarkStore.updateLandmark()

javax.microedition.location.LandmarkStore.category LandmarkStore.addCategory(), LandmarkStore.deleteCategory()

LandmarkStore.createLandmarkStore(),
javax.microedition.location.LandmarkStore.management
LandmarkStore.deleteLandmarkStore()

[Insert Document Type] Page 10