Android Core

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 :

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

49 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
santosh kumar
santosh kumar
12 years ago

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

santosh kumar
santosh kumar
12 years ago

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

Grim Reaper
Grim Reaper
12 years ago

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

mudassar
12 years ago

thank u sssssssssssssssooooooooooooooo much dare

Salman Hussain
11 years ago
Reply to  mudassar

hello there, can u please guide me as to how this thing works? as in step wise procedure to successfully run this project

eric
12 years ago

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

batselem
12 years ago

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?

Yogesh Solanki
11 years ago
Reply to  batselem

i am having the same problem please tell me how to solve it if you have solved it.

Muhammad Saqib Iqbal Mughal
Reply to  Yogesh Solanki

have u got any solution

Bhuvan Chandra
Bhuvan Chandra
11 years ago

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

Salman Hussain
11 years ago
Reply to  Bhuvan Chandra

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

yogendra G
yogendra G
11 years ago

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

Syed Ibtisam Tauhidi
11 years ago
Reply to  yogendra G

change uses-sdk android:minSdkVersion=”3″ in the manifest to the value you need

siddarthm
siddarthm
11 years ago

I have changed this but it still wont work on the real device. Any further help would be appreciated

Hoàng Hưng
Hoàng Hưng
11 years ago

Great!

ola
ola
11 years ago

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

Levi Sukma
Levi Sukma
11 years ago

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
Bishnu Trivedi
10 years ago
Reply to  Levi Sukma

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

Lily
Lily
11 years ago

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

asampayo
asampayo
10 years ago

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?

tushar pandey
tushar pandey
10 years ago

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

bitz!
bitz!
10 years ago

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

Jess
Jess
10 years ago

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.

Ravi Agarwal
Ravi Agarwal
10 years ago

awesome but where is the next tutorial ????

Prabakaran
Prabakaran
10 years ago

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

moni
moni
10 years ago

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

JanakSinh
JanakSinh
9 years ago

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

Back to top button