Android provides Location-based Services (LBS) that let users know about their current location, current traffic conditions, and places nearby. In addition, Android provides techniques that let you find, contextualize, and map geographical locations. Android also allows you to create map-based activities by using Google Maps as a UI element. In addition, it allows you to use overlays to annotate maps.
Identifying Location-based Services
LBS are information services that are accessible within mobile devices through the Internet via either mobile network data services, such as General Packet Radio Service (GPRS), or Internet Wi-Fi services. LBS provide information about your device’s current location. To understand the use of LBS, consider a scenario where you are on a vacation and want to go to a Chinese restaurant for dinner in the new city. The only gadget you are carrying is your smartphone. You can use the LBS available on your smartphone to locate an appropriate, nearby restaurant. To search for an appropriate restaurant, you can use the search criteria that include the name of the city where you are and the type of restaurant, and then use your smartphone to get directions to the selected restaurant by using LBS. The LBS would provide you all the possible results based on your search criteria and possibly your location. Typical apps of LBS are location identification, fleet management, emergency services, travel aids, and vehicle navigation. In order to provide LBS, your device needs to accurately determine your location so that it can help you with the right information. To identify your location, your mobile device can make use of the various location providers, such as:
- Global Positioning System (GPS)
- Cell tower triangulation
- Public Wireless Fidelity (Wi-Fi) hotspots
The GPS is a satellite-based navigation system and uses a network of satellites to provide location-related information. It uses satellites to track the position of objects on Earth. A GPS receiver or GPS-enabled device locates three or more of these satellites, figures out the distance to each, and uses this information to deduce its own location. The receiver calculates the position of objects in two-dimensional space as well as in three-dimensional space by using a mathematical principle called trilateration. Trilateration can be of two types, two dimensional (2-D) and three dimensional (3-D).
Imagine that you are driving through an unfamiliar country and you are lost. You find a road sign indicating that you are 500 miles away from the city A. However, this much information is not enough as you could be anywhere in a circle of 500 miles radius from the city A. You then stop a passerby to ask for directions and you come to know that you are 450 miles away from the city B. Now, you are in a better position to locate yourself. You find that you are at one of the two intersecting points of the two circles surrounding the city A and the city B. If you could also get your distance from another place say the city C, you can locate yourself precisely, as these three circles can intersect each other at just one point. This is the principle behind 2-D trilateration. The following figure depicts the process of 2-D trilateration.
Figure 1: The Process of 2-D Trilateration
Fundamentally, 3-D trilateration is quite similar to 2-D trilateration. In 3-D trilateration, a GPS receiver needs to find the distance to three satellites of known positions. If the receiver finds that it is x miles from one satellite, it knows that it must be somewhere on an imaginary sphere of the radius x miles, with the satellite at the center of the sphere. If the receiver can generate these spheres for two satellites, it knows it can only be located where the surfaces of the two spheres intersect. The two spheres overlap in a ring of possible receiver positions. By generating a sphere for a third satellite, the receiver narrows its possible positions down to two points. The receiver dismisses the point located in space, leaving only one possible position. The following figure depicts 3-D trilateration.
Figure 2: The 3-D Trilateration
Some common uses of GPS are:
- GPS can be used to navigate your car through traffic and find your way to any destination.
- Laptop GPS receivers can be used for in-vehicle, office-based meetings to track locations and get directions.
- GPS-equipped mobile devices can transmit precise locations to emergency call receivers. This helps obtain an immediate and accurate location instead of relying upon descriptions of people who may be unfamiliar with the area or too distraught to explain their location.
- GPS is often used by hikers, hunters, snowmobilers, mountain bikers, and cross-country skiers.
- GPS in public transportation, such as flights, rails, buses, and taxis, helps commuters to track availability and schedule in real time.
- GPS is a vital resource for police, fire, and emergency medical-service units. These units use GPS receivers to find out if a police patrol, a fire engine, or an ambulance is near an emergency hit area, enabling quick response in a life-or-death situation.
- GPS can be used to protect your near and dear ones by tracking their whereabouts.
- You can also use GPS for asset protection. For example, GPS can be used in vehicles to prevent theft.
Cell Tower Triangulation
Cell tower triangulation is yet another technique for obtaining the current position of a mobile device, whether stationary or moving. Most mobile networks work on the concept of cellular networks. A cellular network is a radio network spread over land areas in beehive shaped hexagonal cells. Each cell has at least one fixed-location transceiver known as a cell tower or base station, whose geographical location is known and visible. Together, these cells provide a signal coverage spread over a large geographic area such as a city or country. The cell towers enable mobile devices such as cell phones to communicate with each other and with fixed transceivers or telephone networks anywhere, even if some of the transceivers are moving through more than one cell during the transmission. Location can be determined by measuring the signal strength from the nearest cell tower. It works on the basic principle that a mobile device always communicates with one of the closest cell towers. Therefore, if you know which cell tower the device is communicating with, you know that the device is close to the respective cell tower. The cell tower triangulation technique refers to the process of determining the location of a device by measuring its angles with the known cell towers. It does not measure distances between points directly, as in the case of trilateration. The cell tower triangulation technique determines the location of the mobile device by computing its location by identifying neighboring cells and their signal strengths.
Public Wi-Fi Hotspots
In addition to GPS and cell tower triangulation, public Wi-Fi hotspots can be used to determine the location of a device. This technique performs best where GPS is the weakest, for example indoors where there is no line of sight between the device and the satellites. In such a situation, the proximity of a device to known Wi-Fi hotspots can be used to determine its current location. This location may not be as accurate as is provided by GPS. Determining the location of a device by using public Wi-Fi hotspots requires the service provider to conduct periodic sweeps of an area to collect data about public Wi-Fi hotspots. This data is collected in a variety of ways, for example, by using the information provided by cellphone handsets, computer applications, and radio receivers attached to vehicles. The vehicles used for collecting the information about Wi-Fi hotspots are fitted with radio receivers that receive publicly broadcasted Wi-Fi radio signals within the range of the vehicle. The data collected by the radio receivers is used to compile the LBS database. The following two pieces of information are used to build the database:
- The Media Access Control (MAC) address of the hotspot.
- The GPS coordinates of the vehicle at the point when the hotspot was visible.
To determine the location of a device, the following process is used:
The device sends a request to the location server with a list of MAC addresses currently visible to the device. Then, the location server compares the list of MAC addresses with the list of MAC addresses of known Wi-Fi hotspots to identify matching MAC addresses and their corresponding geographical locations.
The location server determines the approximate location of the device by using the geographical locations of the visible MAC addresses to triangulate the approximate location of the user.
To maintain an accurate database, service providers need to constantly update the catalog of hotspots by conducting periodic sweeps of an area to collect information about Wi-Fi hotspots. Otherwise, the technology’s accuracy may be impacted because of the changing dynamics of hotspots.
Working with Location-based Services
The Android SDK provides the APIs necessary for retrieving the location data based on a variety of methods including: GPS sensors, cell tower triangulation, and Wi-Fi hotspots. Once your location is determined, you can then work with other APIs, such as the Google Maps API, to create intuitive and useful map-based apps that can automatically display a map and pinpoint your current location on it. The two main classes used in any LBS-enabled app are:
LocationManager: Provides access to a device’s location services. Using the location manager, an app can:
- Get periodic updates on the device’s current location.
- Set proximity alerts to detect the movement into and out of a specified geographic location.
LocationProvider: Is the base class for all types of location providers. Location providers provide periodic updates about the location of a device.
Accessing Location-based Services
LBS-enabled apps expose the user’s personal and location information and can be subject to a privacy breach. Moreover, using LBS consumes a large amount of network data storage and battery of the device. In order to ensure a good user experience, you can demand requisite permissions from the end users to allow the use of LBS. To access LBS, use the LocationManager system service of the Android platform. To access the LocationManager system service, you need to get an instance of the LOCATION_SERVICE service by using the getSystemService()method, as shown in the following code snippet:
String serviceString = Context.LOCATION_SERVICE; LocationManager locationManager; locationManager = (LocationManager) getSystemService(serviceString);
Apps cannot use LBS unless they have included the requisite permissions in the AndroidManifest.xml file. The common permissions used by apps to access LBS are:
- android.permission.ACCESS_FINE_LO CATION: This permission is used to receive location settings from a GPS provider.
- android.permission.ACCESS_COARSE_ LOCATION: This permission is used to receive location settings from a mobile network provider.
The GPS provider uses the fine permission and the mobile network provider uses only coarse permissions. An app that uses the fine permission will have the coarse permission granted implicitly. The following code snippet shows how to declare the permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCES S_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCES S_COARSE_LOCATION"/>
Besides setting permissions, you need to follow and implement some guidelines in your LBS-enabled apps, such as:
- Inform the users before collecting their personal data, as information about their present or past locations may be sensitive.
- Allow the users to configure and disable features that might adversely affect their experience when using LBS-based apps, such as the option to disable and enable GPS receiver or the option to restrict sharing the current location information over the network.
- Handle other events, such as low battery, or other warnings in your app and notify the user about these events.
Selecting a Location Provider
There are several technologies available for Android devices to determine the current location of the device. Each technology, referred to as a location provider, offers a different set of features, such as the power consumption, monetary cost, accuracy, and the ability to determine the altitude, speed, or heading information. Based on your requirement, you can select a suitable location provider for your device.
Searching for Location Providers
The LocationManager class provides access to the system location services, which allow apps to obtain periodic updates of the device’s geographical location. This class also allows you to send an app-specified Intent when the device enters the proximity of a given geographical location. The LocationManager class also includes static string constants that return the provider names for the two most commonly-used location providers.
Creating Map-based Apps
One of the ideal ways to provide the context for a physical location or address is to display it on a map. The Map view provides a compelling UI for presentation of geographical data. Map views provide full programmatic control of the map’s display and allow users to control the zoom, location, and display modes of maps including the option to display satellite, street, or traffic views. On the Android platform, you can display maps either by using Google Maps or a similar service and displaying it in the Web browser, or by creating an app that uses the Goggle Maps API or a similar maps API.
Using the MapFragment Class
You can add maps to your apps by using the Google Maps API, which is based on the Google Maps data. This API handles the various tasks, such as access to Google Maps servers, data downloading, map display, and touch gestures on the map.
The com.google.android.gms.maps.MapFragment class provides all the UI elements that are necessary for users to control the map. A map fragment is added to an activity layout file, as shown in the following code snippet:
<fragment android:id="@+id/map"android:name="com.google.android.gms.m aps.MapFragment" android:layout_below="@+id/header"android:layout_width="match_parent"android:layout_height="match_parent" />
By default, a simple map is displayed, as shown in the following figure.
Figure 3: The Simple Map View
Creating a Map-based Activity
To use maps in your apps, you need to create a new activity that extends the Activity. The Android map library is not a standard package and therefore, it must be explicitly included in the app’s manifest file before using it.
Google Maps downloads the map from the Internet and also requires setting the permission to use the same in the AndroidManifest.xml file, as shown in the following code snippet:
<permission android:name="com.example.android.mape xample.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="com.example.android.mape xample.permission.MAPS_RECEIVE"/> <uses-permission android:name="android.permission.INTER NET"/> <uses-permission android:name="android.permission.ACCES S_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE _EXTERNAL_STORAGE"/> <uses-permission android:name="com.google.android.provi ders.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCES S_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCES S_FINE_LOCATION"/>
Once you have added the library and configured your permission, you can start creating your new map-based activity.
Let’s concentrate on the scenario that loads Google map and the current device location.
You must have a working Google account.
To develop the map based app, you need to perform the following tasks. First of all, you have to download Google Play Services, create a new Android application project, create the UI for the app, generate the API key for the app and then modify the Android manifest file.
Downloading Google Play Services
To download Google Play Services, you need to perform the following steps:
Open the Eclipse IDE and select Window > Android SDK Manager. The Progress Information dialog box is displayed, as shown in the following figure.
Figure 4: The Progress Information Dialog box
After a few seconds, The Android SDK Manager window is displayed.
Scroll down the Packages list, and then select the Google Play services check box under the Extras node, as shown in the following figure.
Figure 5: Google Play services Under the Extras Node
Ensure that no other options are selected and then click the Install 1 package button. The Choose Packages to Install window is displayed. Select Google Play services, and then select the Accept option. Click the Install button. The download will be started.
After the download is complete and Google Play services are installed, close the Android SDK Manager window. Switch to Eclipse IDE and select File>Import. The Import window is displayed, select the Existing Android Code Into Workspace node under the Android node. Click the Next button. The Import Projects screen is displayed.
Click the Browse button. The Browse For Folder dialog box is displayed. Browse to the adt-bundle-windows-x86_64-20130522\sdk\extras\google\google_play_services\libproject\google-play-services_lib directory on your computer. Click the OK button to close the Browse For Folder dialog box.
The google-play-services_lib project is added to the Projects section in the Import Projects screen. Select the Copy projects into workspace check box and Click the Finish button. The google-play-services_lib project is imported into the workspace.
Creating a New Android Application Project
To create a new eclipse project, you need to perform the following steps:
Ensure that the Eclipse IDE is open. Select File>New>Android Application Project. The New Android Application window is displayed.
Type GMap in the Application Name text box and click the Next button. The next screen of the New Android Application window that helps to configure the project is displayed.
Leave the default selections, and then click the Next button. The Configure Launcher Icon screen of the New Android Application window that helps you create a launcher icon for your app is displayed.
Click the Next button. The Create Activity screen of the New Android Application window that helps to create an activity is displayed.
Ensure that the Create Activity check box and the Blank Activity option are selected.
Click the Next button. The Blank Activity screen of the New Android Application window is displayed.
Click the Finish button. A new project with the name GMap is created in the Package Explorer window.
Creating the UI for the App
- To create the UI for the app, you need to perform the following steps:
- Ensure that the GMap?res nodes are expanded in the Package Explorer window.
- Ensure that the activity_main.xml file is displayed in the Editor area.
- Click the activity_main.xml tab at the bottom of the Editor area.
- Add the highlighted portions of the following markup:
<RelativeLayout xmlns:android="http:// schemas.android.com/apk/res/ android" xmlns:tools="http:// schemas.android.com/tools" android:layout_width="match_paren t" android:layout_height="match_pare nt" android:paddingBottom="@dimen/ activity_vertical_margin" android:paddingLeft="@dimen/ activity_horizontal_margin" android:paddingRight="@dimen/ activity_horizontal_margin" android:paddingTop="@dimen/ activity_vertical_margin" tools:context=".MyMapActivity" > <TextView android:id="@+id/header" android:layout_width="wrap_conten t" android:layout_height="wrap_content" android:text="@string/ hello_world" /> <fragment android:id="@+id/mymap" android:name="com.google.android. gms.maps.MapFragment" android:layout_below="@+id/ header" android:layout_width="match_paren t" android:layout_height="match_pare nt" /> </RelativeLayout>
Select File>Save All, Right-click the GMap node in the Package Explorer window, and then select Properties. The Properties for GMap window is displayed. Ensure that the Android node is selected in the left pane.
Click the Add button in the right pane. The Project Selection window is displayed. Select the google-play-services_lib library project.
Click the OK button to close the Project Selection window. The google-play-services_lib library project is added in the Library list box in the right pane of the Properties for GMap window. Click the OK button.
Generating the API Key for the App
To generate the API key for the app, you need to perform the following steps:
Open command prompt, go to the bin folder of the Java installation and type the following command and Press the Enter key:
keytool -list -v -keystore "C: \Users\<username>\.android \debug.keystore" -alias androiddebugkey -storepass android -keypass android
You need to enter the username in the preceding command.
If prompted to enter a password, then enter android (or your modified password if any) as the password and then press the Enter key.
The following figure shows the output of the preceding command.
Figure 6: The keytool Command Output
You need to note down the SHA1 fingerprint and it will be used in the further steps.
Note: The certificate fingerprints are unique for your machine. Therefore, it is essential to generate new certificate fingerprints for each machine.
Open https://code.google.com/apis/console/#project:486217353208 in the browser window. The Google Accounts page is displayed, as shown in the following figure.
Figure 7: The Google Accounts Page
Type your username in the Email text box, type your password in the Password text box and click the Sign in button. The Google API Console page is displayed.
Note: If the AutoComplete Passwords dialog box is displayed, then click the No button to proceed further.
Click the Services link. The All services page is displayed.
Scroll down the page, and then ensure that the status of the button located next to the option is displayed as:
Figure 8: Status of the button
Note: If the status is off, then you need to click the button to set it to on.
Scroll up the page, and then click the API Access link. The API Access page is displayed.
Click the Create new Android key button. The Configure Android Key for API Project dialog box is displayed, as shown in the following figure.
Figure 9: The Configure Android Key for API Project Dialog Box
Type the<SHA1 fingerprint>;com.example.gmap in the Accept requests from an Android application with one of the certificate fingerprints and package names listed below text box, and then click the Create button.
The API key will be generated. You need to note down or copy the API key.
Modifying the Android Manifest File
You need to modify the Android manifest file to declare permissions required for accessing the Internet and location services. In addition, you need to declare that the app uses the Google maps library.
First, double-click the AndroidManifest.xml file under the GMap node in the Package Explorer window. The GMap Manifest file is displayed in the Editor area. Then click the AndroidManifest.xml tab located at the bottom of the Editor area.
Type the following markup before the <application> tag to declare permissions:
<permission android:name=“com.example.gmap.p ermission.MAPS_RECEIVE” android:protectionLevel=“signatu re”/> <uses-permission android:name=“com.example.gmap.pe rmission.MAPS_RECEIVE”/> <uses-permission android:name="android.permission. INTERNET"/> <uses-permission android:name=“android.permission. ACCESS_NETWORK_STATE”/> <uses-permission android:name=“android.permission. WRITE_EXTERNAL_STORAGE”/> <uses-permission android:name=“com.google.android. providers.gsf.permission.READ_GSE RVICES”/> <uses-permission android:name=“android.permission. ACCESS_COARSE_LOCATION”/> <uses-permission android:name=“android.permission. ACCESS_FINE_LOCATION”/> <uses-feature android:glEsVersion=“0x00020000” android:required=“true”/>
Type the following markup before the tag:
<meta-data android:name=“com.google.android .maps.v2.API_KEY” android:value=“YOUR_API_KEY”/>
Note: Replace your API key with YOUR_API_KEY in the preceding markup.
Select File Save All.
Note: In order to run this app, you need to use a real device instead of the emulator.
Well, this is how you can create your own map app which will load the map your current location.