Home » Android » Android Core » Android Location Based Services Application – GPS location

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services, currently the technical lead in a in-house PCRF solution. Particularly interested in multi-tier architecture, middleware services and mobile development (contact). Ilias Tsagklis 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 our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

45 comments

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

  2. 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. What file does the LocationManger, getSystemService, etc. reside? 

  4. thank u sssssssssssssssooooooooooooooo much dare

  5. 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. 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. 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. this sample code not working for android 2.3.x.x (Gingerbread). So give some solution for the same.

  9. 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

  10. 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?

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

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

  12. 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?

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

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

  15. 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.

  16. awesome but where is the next tutorial ????

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

  18. 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..

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

  20. 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 ?

  21. Hey its working for me. Thankssssss

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

  23. when i click the button nothing is appearing

  24. can you please send me the source code for location based profile changer to built an android application???

  25. hey, it cant working for me! can u help me?plz

  26. Hello, i am in China. I tried this code. it is not working for me. As Google services are not working in China. Is this could be reason?

  27. I am amin from Iran.
    The code runs without error.
    Bent Gps start the search.
    But it does not show coordinates.
    Please help me.

  28. hi Ilias Tsagklis sir,
    When i try to run ur android location based application code, it gets stopped.
    can u plz give me some solution for tht??

  29. i want shortest path like if i search medicals the medicals near me appear in the form of marker (i already done this) after that the shortest path is selected and show the distance and polyline
    2) i want all medical stores show in a list and order by shortest distance
    plz help

  30. gyz issue is this code is not working on real device just useful to run on Emulator only

  31. This will come handy for some of my future projects. How is this tutorial woking on Android 5 Lollipop?

  32. how to get long and lat for only one time? because it makes toast after every second any help?

  33. salam dear. i need to code of my project if any one have this code or any documents please kindly send me for my project and guide me how i can start my project (location based alarm system using gps in android ) please …

Leave a Reply

Your email address will not be published. Required fields are marked *

*


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.