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.

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

  1. santosh kumar says:

    if u got any answer send to my mail santosh_kumar5671@yahoo.com

  2. santosh kumar says:

    Hi i am doing my project on beagle-board using android Java my work is show the Google map on beagle board and finding lat and long values dynamically can find it in android Java in beagle-board how to start can any one help me please

  3. Grim Reaper says:

    What file does the LocationManger, getSystemService, etc. reside? 

  4. mudassar says:

    thank u sssssssssssssssooooooooooooooo much dare

  5. eric says:

    I had to change the MINIMUM_TIME_BETWEEN_UPDATES to 1 minute because my phone went crazy when it was set to 1 sec and was unable to set a location

  6. batselem says:

    hi. thanks for the tutorial. I have a problem. It works very well in the Eclipse. But when it works in the android phone, it has some misunderstanding thing. Because in this case we can set up the initial location using DDMS(send button). But how can I set up it in my phone?

  7. Bhuvan Chandra says:

    hey i have tried this method it works fine..but i want these coordinates to be sent to a server through internet from the mobile automatically from which i could retrieve the coordinates and overlay them on a map . Can anyone help me how to do that…ASAP ..iam doing it as a part of my project so please help

    • hello there, can u please guide me as to how this thing works? as in step wise procedure to successfully run this project, plus i am doing the same project as your doing i,e transmitting these co ordinates on to a server if your done with that kindly help me as well. ill be waiting for you respons

  8. yogendra G says:

    this sample code not working for android 2.3.x.x (Gingerbread). So give some solution for the same.

  9. Hoàng Hưng says:

    Great!

  10. ola says:

    Hi, Thanks for this tutorial, I tried it and it worked but not as appropriate. It fires the intent immediately irrespective of the location of the device. It does not get to the point of interest before giving the alert. Mine is a bit differnent from yours as I have another textbox that allows the user to enter the destination, then geocode that location and put it’s latitude and longitude into another textbox. I think my problem is that it does not get the latitude and longitude in the textbox and just fires the intent. Pls any advice?. Thank you

  11. Levi Sukma says:

    Hai, thanks a lot for your tutorial. I try to use all of your program to my juno eclipse, and i get error with override.
    @override
    public void onClick(View v){
    showCurrentLocation();
    }
    I don’t know why, I’m new in android. could you give me same solution?

    • Bishnu Trivedi says:

      u should import the package of onClickListener..
      u can do it by pressing ctrl+shift+O by getting a mouse pointer over the error..

  12. Lily says:

    Hye.. I want to ask you..Is it possible to track people in the building using GPS?

  13. asampayo says:

    hi

    how i can my current location when my location changed

    i am use

    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.gpsresults);

    //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()
    );

    showCurrentLocation();

    }

    protected void showCurrentLocation() {

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

    Double lat=0.0;
    Double lon=0.0;

    if (location != null) {
    lat = location.getLatitude();
    lon = location.getLongitude();
    }

    }

    with this i get my location, but when change my location not update latitude and longitude, always get the last location, how i can update my location?

  14. tushar pandey says:

    just go to , bottom left of the page there is white icon , press it and you will find emulator Control tab there .

  15. bitz! says:

    Hi,Great thanks for the tutorial.I would wish to know how i can store the gps location into a mysql database?

  16. Jess says:

    How come we have the same current location?
    Are the values we’ve gotten for the latitude and longitude were the default values (except for 0) or we need an actual device for accurate measurements? Hope you’ll reply thanks in advanced.

  17. Ravi Agarwal says:

    awesome but where is the next tutorial ????

  18. Prabakaran says:

    hi…
    really very nice explanation….by how i can get an accurate location..can u help me..?

  19. moni says:

    sir,
    can i get the code for the above gps location finder but included feautures as to identify hospitals and atm location..plz help me to figure out this..

  20. JanakSinh says:

    I can’t run this application in Device,
    I can’t get result like a emulator result in device

Leave a Reply


one × = 6



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