You are on page 1of 29

Android Location-Based Services

Android Location-Based Services 1


.

Introduction
• A location-based service, or LBS, is any information,
entertainment, or social media service that is
available on a mobile device, through the mobile
network and which uses information on the
geographical position of the mobile device.

Android Location-Based Services 2


.

Introduction
• LBS are used in a variety of contexts, such as
health, indoor object search, entertainment, work,
personal life, etc.
• Examples:
• services to identify a location of a person or object, such as
discovering the nearest banking cash machine or the
whereabouts of a friend or employee.
• parcel tracking and vehicle tracking services.
• mobile commerce when taking the form of coupons or
advertising directed at customers based on their current
location.
• personalized weather services and even location-based
games.

Android Location-Based Services 3


2-D Trilateration
• In geometry, trilateration is the process of determining
absolute or relative locations of points by measurement of
distances, using the geometry of circles, spheres or triangles.
Imagine you are somewhere in the United States.
If you are 625 miles from Boise, you could be anywhere
on a circle around Boise that has a radius of 625 miles.

If you are 690 miles from Minneapolis, you now know


that you must be at one of these two intersection points,
if you are 625 miles from Boise and 690 miles from
Minneapolis.

If you are 615 miles from a third reference point


Tucson, you can eliminate one of the possibilities
because the third circle will only intersect with one of
these points. You now know exactly where you are –
Denver.

Reference:http://electronics.howstuffworks.com/gadgets/travel/gps1.htm
Android Location-Based Services 4
3D-Trilateration
• This same concept works in three-dimensional
space, as well, but you're dealing with spheres
instead of circles.
• For a visual explanation visit:
http://electronics.howstuffworks.com/gadgets/travel
/gps.htm

Reference : http://electronics.howstuffworks.com/gadgets/travel/gps2.htm
Android Location-Based Services 5
GPS
• The Global Positioning System (GPS) is
originally a constellation of 24 Earth-
orbiting satellites in 6 orbital planes with
4 satellites each.
• The orbits are arranged so that at any
time, anywhere on Earth, there are at
least four satellites "visible" in the sky.
• A GPS receiver's job is to locate four or
more of these satellites, figure out the
distance to each, and use this
information to deduce its own location.
• This operation is based on a simple
mathematical principle called
trilateration.
Reference: http://electronics.howstuffworks.com/gadgets/travel/gps.htm
Android Location-Based Services 6
Cell Tower Triangulation
• An alternative method to determine the
location of a cell phone is to estimate
its distance to three nearby cell towers.
• A cell phone’s signal may be picked up
by three or more cell towers, enabling
the “triangulation” to work.
• Since we know the locations of the cell
towers which receive the phone’s
signal, and we can estimate the
distance of the phone from each of
those antennae towers, based upon the
lag time between when the tower
sends a ping to the phone and receives
the answering ping back.
Reference: http://searchengineland.com/cell-phone-triangulation-accuracy-is-all-over-the-map-14790
Android Location-Based Services 7
Geographic coordinate system
• A geographic coordinate system is a coordinate system that
enables every location on the Earth to be specified by a set
of numbers or letters.
• A common choice of coordinates is latitude, longitude and
elevation.
• Latitude in GPS-Decimal notation: +90.00000 (North) to -
90.000000 (South).
• Longitude GPS-Decimal notation: +180.000000 (East) to -
180.000000 (West).

Android Location-Based Services 8


Android Location Classes
• Android gives your applications access to the location
services supported by the device through classes in
the android.location package.
A class representing an Address, i.e, a set of Strings
Address
describing a location. 
A class indicating the application criteria for selecting a
Criteria
location provider. 
Geocoder A class for handling geocoding and reverse geocoding. 

Location A data class representing a geographic location. 

LocationManager This class provides access to the system location services. 

LocationProvider An abstract superclass for location providers. 

Used for receiving notifications from the LocationManager


LocationListener
when the location has changed. 

Android Location-Based Services 9


Android Location Classes
• Location class
• A class representing a geographic location.
• A location can consist of a latitude, longitude, timestamp,
and other information such as bearing, altitude and velocity.
• Location Manager
• This class provides access to the system location services.
• These services allow applications to obtain periodic updates
of the device's geographical location,
• or to fire an application-specified Intent when the device
enters the proximity of a given geographical location.
• You do not instantiate this class directly; instead, retrieve it
through
Context.getSystemService(Context.LOCATION_SERVICE).

Android Location-Based Services 10


Android Location Classes
• Location Listener
• Used for receiving notifications from the LocationManager
when the location has changed.
• These methods are called if the LocationListener has been
registered with the location manager service using the
method:
requestLocationUpdates (String provider, long minTime, float
minDistance, LocationListener listener)

onLocationChanged(Location location)
abstract void
Called when the location has changed.

onProviderDisabled(String provider)
abstract void
Called when the provider is disabled by the user.

onProviderEnabled(String provider)
abstract void
Called when the provider is enabled by the user.

onStatusChanged(String provider, int status, Bundle extras)


abstract void
Called when the provider status changes.
Android Location-Based Services 11
Android Location Classes
• Location Provider
• An abstract superclass for location providers.
• A location provider provides periodic reports on the
geographical location of the device.
• Each provider has a set of criteria under which it may be
used; for example,
 some providers require GPS hardware and visibility to a
number of satellites;
 others require the use of the cellular radio,
 or access to a specific carrier's network,
 or to the internet.
• They may also have different battery consumption
characteristics or monetary costs to the user.
• The Criteria class allows providers to be selected based on
user-specified criteria.

Android Location-Based Services 12


Example – Obtain Location from GPS
• The following examples shows how to obtain a
location in Latitude and Longitude by using GPS.

Android Location-Based Services 13


Example – Obtain Location from GPS
• Declare Proper Permissions in Android Manifest
• The first step of setting up location update access is to
declare proper permissions in the manifest. If permissions
are missing, the application will get a SecurityException at
runtime.
• Depending on the LocationManager methods used, either
use ACCESS_COARSE_LOCATION (if uses a network-based
location provider only) permission;
• or use ACCESS_FINE_LOCATION permission (for accurate
GPS). Declaring the ACCESS_FINE_LOCATION permission implies
ACCESS_COARSE_LOCATION already.
◦ Also, if a network-based location provider is used in the
application, you'll need to declare the internet permission as
well.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Android Location-Based Services 14


Example – Obtain Location from GPS
• Get a Reference to LocationManager
• LocationManager is the main class through which your
application can access location services on Android.
• Similar to other system services, a reference can be obtained
from calling the getSystemService() method.
• If your application intends to receive location updates in the
foreground (within an Activity), you should usually perform
this step in the onCreate() method.

LocationManager locationManager =
        (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

Android Location-Based Services 15


Example – Obtain Location from GPS
• Pick a Location Provider
• Location providers may have different performance
characteristics in terms of time-to-fix, accuracy, monetary
cost, power consumption, and so on.
• Generally, a location provider with a greater accuracy, like
the GPS, requires a longer fix time than a less accurate one,
such as a network-based location provider.
• Depending on your application's use case, you have to
choose a specific location provider, or multiple providers,
based on similar tradeoffs.
• The snippet below asks for a location provider backed by
GPS.

LocationProvider provider =
        locationManager.getProvider(LocationManager.GPS_PROVIDER);

Android Location-Based Services 16


Example – Obtain Location from GPS
• Pick a Location Provider
• Alternatively, you can provide some input criteria such as
accuracy, power requirement, monetary cost, and so on,
• and let Android decide a closest match location provider.
• The snippet below asks for a location provider with fine
accuracy and no monetary cost.
// Retrieve a list of location providers that have fine accuracy, no monetary
cost, etc
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
...
String providerName = locManager.getBestProvider(criteria, true);

// If no suitable provider is found, null is returned.


if (providerName != null) {
   ...
}
Android Location-Based Services 17
Example – Obtain Location from GPS
• Set Up the Location Listener
• To receive location updates, you can register an event
listener, identify the location manager from which you'd like
to receive location updates,
• and specify the minimum time and distance intervals at
which to receive location updates.
• The onLocationChanged() callback will be invoked with the
frequency that correlates with time and distance intervals.
• The other callback methods notify the application any status
change coming from the location provider.

Android Location-Based Services 18


Example – Obtain Location from GPS
• In the sample code snippet below, the location listener is set
up to receive notifications at least every 10 seconds and if
the device moves by more than 10 meters.

private final LocationListener listener = new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {
        // A new location update is received.  Do something useful with it.  
            ...
    }
    ...
};
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        10000,          // 10-second interval.
        10,             // 10 meters.
        listener);

Android Location-Based Services 19


Example – Obtain Location from GPS
• Use getLastKnownLocation()
• The setup time for getting a reasonable location fix may not
be acceptable for certain applications.
• You should consider calling the getLastKnownLocation()
method which simply queries Android for the last location
update previously received by any location providers.
• The returned location may be stale.
• You should check the timestamp and accuracy of the
returned location and decide whether it is useful for your
application.

Android Location-Based Services 20


Example – Obtain Location from GPS
• Terminate Location Updates
• When you are done with using location data, you should
terminate location update to reduce unnecessary
consumption of power and network bandwidth.
• For example, by calling removeUpdates().

protected void onStop() {


    super.onStop();
    mLocationManager.removeUpdates(listener);
}

• Get the geographic coordinates


• Obtain the Latitude and Longitude (in degrees) from
Location by using getLatitude() and getLongitude() methods.

Android Location-Based Services 21


Challenges in Determining User Location
• There are several reasons why a location reading
(regardless of the source) can contain errors and be
inaccurate. Some sources of error in the user
location include:
• Multitude of location sources - GPS, Cell-ID, and Wi-Fi can
each provide a clue to users location. Determining which to
use and trust is a matter of trade-offs in accuracy, speed,
and battery-efficiency.
• User movement - Because the user location changes, you
must account for movement by re-estimating user location
every so often.
• Varying accuracy - Location estimates coming from each
location source are not consistent in their accuracy. (A
location obtained 10 seconds ago from one source might be
more accurate than the newest location from another or
same source.)

Android Location-Based Services 22


Geocoding and Reverse Geocoding
• Geocoding is the process of translating a description
of a location into GPS coordinates (latitude,
longitude, and sometimes altitude).
• Geocoding enables you to enter a place name such
as Eiffel Tower into Google Maps
(http://maps.google.com) and get the appropriate
spot on the map.
• Reverse Geocoding can translate raw coordinates
into some form of address.
• The Android SDK includes the Geocoder
(Android.location.Geocoder) class to facilitate
interaction with the handset’s geocoding and
reverse-geocoding services.

Android Location-Based Services 23


Example - Geocoding & Reverse Geocoding
• The following example processes both Geocoding
and Reverse Geocoding.

Android Location-Based Services 24


Example - Geocoding & Reverse Geocoding
• Instantiating a Geocoder is simple:
Geocoder geocoder = new Geocoder(this);

• Geocoding:Translating Addresses into Coordinates


• Geocoded addresses are often ambiguous, so a geocoding
service may return multiple records.
• For example, if you were to try to resolve the address
“Ocean Park,” you would likely get quite a number of results
in the world.

Android Location-Based Services 25


Example - Geocoding & Reverse Geocoding
• You can use the Geocoder class getFromLocationName()
method to resolve a location into coordinates.
• Returns an array of Addresses that are known to describe
the named location.
List<Address> getFromLocationName (String locationName, int maxResults)

Parameters
locationName - a user-supplied description of a location.
maxResults - max number of results to return.
Smaller numbers (1 to 5) are recommended.

• Each Address object returned contains information about the


location.
• You can use the getLatitude() and getLongitude() methods
of the Address class to access the location’s coordinates.

Android Location-Based Services 26


Example - Geocoding & Reverse Geocoding
• Reverse Geocoding: Translating Coordinates into
Addresses
• You can use the Geocoder class’s getFromLocation() method
to translate raw latitude and longitude coordinates into
address information.

List<Address> getFromLocation (double latitude, double longitude, int


maxResults)

Parameters
Latitude - the latitude a point for the search
Longitude - the longitude a point for the search
maxResults - max number of results to return.
Smaller numbers (1 to 5) are recommended.

Android Location-Based Services 27


Background Threads
• For applications that need to continuously receive
and process location updates like a near-real time
mapping application, it is best to incorporate the
location update logic in a background service.
• Like other network operations, geocoding services
also are blocking operations. This means that you’ll
want to put any calls to geocoding services in a
thread separate from the main UI thread.

Android Location-Based Services 28


Mock Location Data by using DDMS
• If your application depends on the location of the
phone, you can have DDMS send your device or
AVD a mock location.
• One of the way to simulate location data can be
made by manually send individual longitude/latitude
coordinates to the device.

Android Location-Based Services 29

You might also like