Published on Jun 02,2015
6.6K Views
Email Post

I believe if our concepts are clear on a particular topic, it does not take much time to understand how to play around with that concept. So, let us start with the concepts first and then we will deal with the actual code development.

Location Based Services In Android – The Concept

We have something known as ‘Location Based Services‘ in Android. Location Based Services are provided by Android through its location framework. The framework provides a location API which consists of certain classes and interface. These classes and interface are the key components which allow us to develop Location Based Application in Android.

Classes and Interfaces of Location Based Services:

LocationManager – This class helps to get access to the location service of the system.
LocationListener – This interface acts as the listener which receives notification from the location manager when the location changes or the location provider is disabled or enabled.
Location – This is the class which represents the geographic location returned at a particular time.

These android built-in components have made it easier for us to get the user location. In this blog post, we will walk through the steps that need to be followed to retrieve user location.

Step 1

An instance of the LocationManager needs to be created as the first step in this process. This is the main class through which the application gets access to the location services in Android. A reference to this system service can be obtained by calling getSystemService() method.

LocationManagerlocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Step 2

Next step is to identify the location provider you would like to use for retrieving location details.
The location providers actually provide the location data in Android. Android exposes two main location providers:

1. GPS Location Provider:

This location provider provides location data with the highest accuracy (~2 m – 20m). Location updates are provided through satellites. However there are some drawbacks with this provider which are explained as below:

A. It is significantly slower than the network provider to get the initial connection setup with the satellites. This initial connection, also called Time to First Fix (TTFF) can be extremely slow but once the connection is established, location updates are quite fast.

B. GPS provider also drains out the battery very first. So, it is very important to judiciously use this provider. Special care should be taken to ensure that this is turned off when you are not using it.

C. The third draw back comes from the fact that GPS uses radio signal which is obstructed by solid objects. So, GPS provider will not work if you are inside a building or in a basement.

2. Network Provider:

This provider uses Wi-Fi hotspots and cell tower to approximate a location. The provider retrieves an approximate location by querying the Google location server using the IDs of the Wi-Fi hotspots and cell towers. Location accuracy is between 100 – 1000 m. The location accuracy is directly proportional to the number of Wi-Fi hotspots and cell towers available in the area.

You can check the availability of the providers using the below piece of code:

isGpsEnabled = mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Step 3

The next step is to register a location listener with the location manager. The registration can be done by calling the method requestLocationUpdates((String provider, long minTime, float minDistance, LocationListener listener).

Following are the parameters passed to this method:

provider:
the name of the provider with which to register. This can be either GPS or Network provider.
minTime:
minimum time interval between location updates, in milliseconds.
minDistance:
minimum distance between location updates, in meters.
listener:
a LocationListener whose onLocationChanged(Location) method will be called for each location update.

The Location Manager calls the onLocationChanged() of the listener when the mobile has moved a distance greater than the minDistance or the time since last location update is more than minTime.

 Location Based Services In Android – The Code

We just brushed up some basic concepts based on Location Based Services in Android. Let us now learn how to exercise those concepts!

1. Prerequisites:

  • One should have the knowledge of how to test location based services in emulator – through the emulator; you can setup mock locations through the emulator control. For this, in the emulator control, type the latitude and longitude and hit the ‘SEND‘ button. This will setup the mock location of the emulator.

Location based services

  • Permissions required for Location Based Services in Android – In the Android manifest file, you will need to specify 3 permissions as mentioned below:
<uses-permissionandroid:name=”android.permission.ACCESS_COARSE_LOCATION”/>
<uses-permissionandroid:name=”android.permission.ACCESS_FINE_LOCATION”/>
<uses-permissionandroid:name=”android.permission.INTERNET”/>

For GPS based location, you need only the “android.permission.ACCESS_FINE_LOCATION
For Network based location, you need only the “android.permission.ACCESS_FINE_LOCATION
If you are using both the providers, you need to request only for the ACCESS_FINE_LOCATION permission, it includes permission for both the providers.

2. Layout:

It is always easy to understand an application if we start from the layout/user interface of the application project. The layout for this sample application looks as below:

Layout

It has 4 views:

1 – This is the label for the latitude.
2 – This text view will be populated with the latitude of the location.
3 – This is the label for the longitude.
4 – This text view will be populated with the longitude of the location.
On click of this button the latitude and longitude will be retrieved and populated in their respective text views.

3. The Code:

Let us now look at the important snippets of the code:

The MainActivity class implements the location listener. This class will be used as the listener and the location manager will register itself to this listener.

publicclassMainActivityextends Activity implementsLocationListener, OnClickListener{

In the OnCreate() method, I am doing 2 important things:

1. Got an instance of the location manager by calling the sodystem service met
mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

2. Checking which location provider is enabled

isGpsEnabled = mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Below is my logic in the OnClick method of the button view. When the button is clicked, I check which provider is enabled. If GPS is enabled, I register the location manager with the location listener (which is this instance of the MainActivity class) using GPS provider, else I use Network Provider. This part is the key. When the requestLocationUpdates method is called, it in turn will call the onLocationChanged method and will pass the location object to that method.

</pre>
@Override
 publicvoidonClick(View v) {
 // TODO Auto-generated method stub
 int id = v.getId();

switch (id) {
 caseR.id.btGetLocation:
 if(isGpsEnabled)
 {
 mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, MainActivity.this);
 } elseif(isNetworkEnabled)
 {

mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 10, MainActivity.this);
 }
 break;

default:
 break;
 }

What happens in the onLocationChanged() method?

</pre>
latitude = loc.getLatitude();
 longitude = loc.getLongitude();
 tvLatitude.setText(String.valueOf(latitude));
 tvlongitude.setText(String.valueOf(longitude));
 mLocManager.removeUpdates(this);

I get the latitude and longitude and then unregister the location manager from the listener.
This is done to save the battery power of the mobile. If you do not code this, this method will try to access the GPS to get more accurate/precise location details of the mobile. But for our purpose we are content by getting the first location that is retrieved from the satellite.

This article introduces you to the concept of using Location Based Services in Android and explains how you can get the latitude and longitude of your mobile location. In the next part, I will explain how you can retrieve address using 0074he latitude and longitude. So, please stay tuned!

Location Based services in Android

Have a doubt in the discussed concepts? Ask our experts!

Stay tuned for more tutorials to learn how to create Android widgets! Happy Learning!

The following resources were used for creating this post: Edureka.in.

You may also like these related posts:

About Author
shivani kapahi
Published on Jun 02,2015

Share on

Browse Categories

Comments
2 Comments