Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Android Location Based Services Application – GPS location

With the incorporation of GPS devices in smartphones, Location Based Services (LBS) have become pretty hot the past few years. The iPhone was the first to give a huge boost to this kind of applications and now Android continues on the same path. In this tutorial, I will show you how to build your first LBS application for Android. The first step is retrieving the user’s current location and then using his coordinates to provide data for that location.In general, the user’s pinpointing on the map is feasible in one of the following ways:

  1. Using the GPS device that comes with the mobile
  2. Using the ID of the Cell that the user is currently served by

The first one is much easier and more accurate (since the second provides only an approximation). Since these days a big number of phones do have GPS devices onboard, we will use the first way. The Android SDK’s emulator can emulate changes in the user’s location and provide dummy data for his coordinates.

Let’s get started by creating a new Android Project in Eclipse. I gave it the fancy name “AndroidLbsGeocodingProject” and used the properties as shown in the following image:

Note that I used the Android 1.5 platform version and “3” as the SDK’s min version. The application is not going to use any of the new super-duper APIs, so I decided to go with one of the first versions for backwards compatibility. It is generally a good idea to support as many versions as possible. You can find information regarding the platform versions and their corresponding market share here.

To start with, we will only add a button which will trigger the retrieval of the current location’s coordinates from a location provider. Thus, the “main.xml” file for the application’s interface will be as simple as this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
 android:id="@+id/retrieve_location_button" 
 android:text="Retrieve Location"
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 />
</LinearLayout>

In order to get started with the location capabilities of the Android API, the first step is to take reference of the LocationManager class, which provides access to the system location services. This is done via the getSystemService of our activity (actually it inherits it from the Context parent class). Then, we request updates of the device’s location using the method requestLocationUpdates. In that method, we provide the name of the preferred location provider (in our case GPS), the minimum time interval for notifications (in milliseconds), the minimum distance interval for notifications (in meters) and finally a class implementing the LocationListener interface. That interface declares methods for handling changes in the user’s location as well as changes in the location provider’s status. All the above can be translated into code as below:

package com.javacodegeeks.android.lbs;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LbsGeocodingActivity extends Activity {
    
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
    
    protected LocationManager locationManager;
    
    protected Button retrieveLocationButton;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
        
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );
        
    retrieveLocationButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurrentLocation();
            }
    });        
        
    }    

    protected void showCurrentLocation() {

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message,
                    Toast.LENGTH_LONG).show();
        }

    }   

    private class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }

    }
    
}

For the LocationListener interface, we implemented the MyLocationListener inner class. The methods in that class just use Toasts to provide info about the GPS status or any location changes. The only interface element is a Button which gets hooked up with a OnClickListener and when it is clicked, the showCurrentLocation method is invoked. Then, the getLastKnownLocation of the LocationManager instance is executed returning the last known Location. From a Location object we can get information regarding the user’s altitude, latitude, longitude, speed etc. In order to be able to run the above code, the necessary permissions have to be granted. These are:

Include those in the AndroidManifest.xml file, which will be as follows:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.javacodegeeks.android.lbs"
      android:versionCode="1"
      android:versionName="1.0">
      
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LbsGeocodingActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> 
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    <uses-sdk android:minSdkVersion="3" />

</manifest> 

Next, use the AVD Manager in order to create a new Android device and make sure that GPS support is included in the features:

Next, use “Run–> Run Configurations…” to create a new configuration for the project:

If you hit Run, the emulator is started, but nothing will really happen when the button is clicked. That is because when the emulator starts, there is no last known location to be retrieved (the Location instance that is returned is null).

We have to feed the emulator with some dummy data. Go to the DDMS view of Eclipse and look for the “Emulation Control” tab. There, among other things, you will find the “Location Controls” section, which can send mock location data to the emulator. In the “Manual” tab, just hit the “Send” button, there are already some coordinates set up.

When the data are sent to the emulator’s GPS device, our listener will be triggered and the current location will be printed in the screen in the form of a Toast notification.

Now, a last known location exists, so if you hit the “Retrieve Location” button, a not null location will be fetched and the coordinates will again be printed in the screen:

That’s it. Now you are able to emulate changes in the user’s location and retrieve updates about them. In the next tutorial, I will show you how to leverage those coordinates in order to provide useful data to the user. For now, you can find the Eclipse project here.

Happy coding!!!

Related Articles :
Related Snippets :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

32 Responses to "Android Location Based Services Application – GPS location"

  1. Pothiraj says:

    hi..
    In this app it shows lag lan. but i need to create current location from destination place road map view ? Do you have any reference ?

  2. Dhnjy18 says:

    Hey its working for me. Thankssssss

  3. Dhruvang Joshi says:

    Its working fine,but we need only city list within 100km from current location. So how to get that. Can u help me????

  4. sath says:

    when i click the button nothing is appearing

Leave a Reply


five × = 35



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close