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:
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:
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:
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:
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!!!
In general, the user's pinpointing on the map is feasible in one of the following ways:
- Using the GPS device that comes with the mobile
- 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 :
- “Android Full Application Tutorial” series
- Android Text-To-Speech Application
- Android Reverse Geocoding with Yahoo API - PlaceFinder
- Install Android OS on your PC with VirtualBox
- Embracing the Android awesomeness: A quick overview
Related Snippets :
How to keep the location record and draw the lines in the map for those location?
ReplyDeleteHow I want to review what I had been to?
Something likes Route Tracking!
hi
ReplyDeletei tried to execute your code bu im getting a lot of errors.
the string.format() command has errors.
is the downloadable code fully correct?
@shoiks
ReplyDeleteHi, what errors are you getting? Do those occur during compilation or run time execution?
Yes, the downloadable project should be just fine. Please check it and let me know.
HI,
ReplyDeleteHow to locate using maps,i mean Something likes Route Tracking!
Well, the application runs, but doesn't fetch the coordinates. Clicked the "retrieve location" button a number of times, but nothing happens. What could be the problem ?
ReplyDeletehi
ReplyDeletei tried to execute your codes and it went well until i Included your last code in the AndroidManifest.xml file , then the folowing error appeared in the second line :
i Multiple annotations found at this line:
- ERROR No resource identifier found for attribute 'versionCode' in package 'android'
- ERROR No resource identifier found for attribute 'versionName' in package 'android'
Cool,
ReplyDeletetry Spoty:
http://www.androidzoom.com/android_applications/spoty/by_matching
A location based reminder app. It also blocks calls and changes the ringer,wifi bluetooth all based on your location
nicely done too
@ allan
ReplyDeleteMost probably, the emulator has not been provided with data regarding the current location. As I say in the post, you have to feed the emulator with some dummy data.
Go to the DDMS view of Eclipse and look for the “Emulation Control” tab.
From the “Location Controls” section, you can send mock location data. Hit the “Retrieve Location” button, after you have done that.
@ abdalla000
ReplyDeleteI believe that your AndroidManifest.xml is not well formatted. Try copy-pasting again its contents or try using the one provided with the downloadable Eclipse project.
Great tutorial!!! Thanks.
ReplyDeleteI tried several tutorials. Your is the best.
I am very interested in GPS services in Android. When are you posting your next tutorial and where can I find it?
Jay
Hi Jay-K,
ReplyDeleteReally glad you liked my tutorial.
You can find the next part here:
http://www.javacodegeeks.com/2010/09/android-reverse-geocoding-yahoo-api.html
Also note that all our Android tutorials can be found here:
http://www.javacodegeeks.com/search/label/Android%20Tutorial
Regards,
Fabrizio
I have a problem when sending mock data to the app.
ReplyDeleteIt only shows a "Provider status changed" message when DDMS sends the data for the first time. When i click on the "Retrieve Location" afterwards, nothing happens.
I have imported the complete project.
What could be the problem?
Thank you for a wonderful tutorial. I notice when I send LAT/LNG data with DDMS that the values are somehow changed by the time the system interprets them. Do you know why this is? I can never get my coordinates to match the hard coded GEO POINT that i put in the system to mark a location with an overlay.
ReplyDeletethanx for such as informative code there is just no compilation error but when i try to feed emulator with some dummy co-ordinates ...there is pop up window saying unable to send command to emulator. please guide me how to corrct the error though i have added gps support while creating avd. thanx
ReplyDeleteHI,
ReplyDeleteThis code help me a lot.Thanks .
hey when i run the same on actual device it returns me null as location object, how to fix it?
ReplyDeleteAs i am completely new bie for and
When I run on android phone, nothing happen except button(its can press)
ReplyDeletehey there is an error in overridding the method public void onClick(View v)in the LbsGeocodingActivity.java file.. i removed the override and it runs but nothing happens when i click retrieve location :(
ReplyDelete@yoo_sousa,appleboy
ReplyDeletePlease do not forget that you have to send some dummy data to the emulator. This is done by using the DDMS view. Check the corresponding part of the tutorial to find out how to do that.
this was very help ful .thanks a lot!!
ReplyDeleted problem is wen i install this on actual phone,it do not show any co-ordinates,wat shud b done??
also based on the co-ordinates i want to fetch corresponding location name wat to do for d same??
pls reply
Hi hrishi,
ReplyDeleteI haven't tried the specific application on a real device, but it should work without problem.
In order to get the location name, you have to perform reverse geocoding. Please check my next tutorial on how to do that:
http://www.javacodegeeks.com/2010/09/android-reverse-geocoding-yahoo-api.html
Regards,
Fabrizio
Hi Fabrizio,
ReplyDeleteThanks for ur prompt reply.The reverse geocoding tutorial also helped me.
The next i want to try out integrating the google maps in android could u help me out in this plz??
Hi again hrishi,
ReplyDeleteAndroid has built-in Google Maps capabilities, so the integration should be really easy. Check out the following article:
http://developer.android.com/resources/tutorials/views/hello-mapview.html
Regards,
Fabrizio
Hi am trying last tow days i am geting location value is null only.... pls tell the correct ans...
ReplyDeleteI use a location listener like the one in your fine tutorial but I can only send coordinates to the emulator twice. After that it doesn't work anymore... any ideas?
ReplyDeletethnx this is really helpful
ReplyDeleteExcellent
ReplyDeleteYour are the best. Thumbs up for ya.
ReplyDeletehai
ReplyDeleteI tried this code ,it is executing perfectly.
But here it is not showing exact output
It is showing Toast with "Provider status changed".
Please suggest me to overcome this error.............
I want to use a EditText instead of only a Button.And when i click on the button then the current location and the string which i give on the EditText..Which change is required in this code...please tell me..
ReplyDeleteI want to use EditText instead of only button.Ant when i click on the sent button then i want to get the current location and the string which i write on the EnditText...please tell me which changed is required in this code....
ReplyDeletehi i am trying to run. but no response coming on Retrieve Location button click????????????
ReplyDeleteThis is not working for me in real device
ReplyDeleteHi. Great Tutorial. Helps me a lot. Looking forward to trying some more from javacodegeeks.
ReplyDeletehad some of the issues esp the string format one and with @overide
ReplyDeleteFor the @override error: Just remove the line
For String format- well I dont know the reasoning but this is what u need to do- create a new project following the steps outlined in the beginning- now just copy paste the AndroidLbsGeocoding.java code given in the tutorial- for the rest of the files just copy them in the workspace from the download section.
(I think some version specific issue creeps up if u dont create the project yourself).
Hi there. I just moved the app to my real phone. It works, but never stop getting new locations. How can I made it to get the location only when the button is pressed?
ReplyDeleteThaks a lot.
Hi there.
ReplyDeletewht is difference Google API level 13 and level 4.
Is level 13 more advanced than level 3 ???
Or are these different in there functionalities??
Hi there,
ReplyDeletethanx for such an informative code there is just no compilation error but when i try to feed emulator with some dummy co-ordinates ...there is pop up window saying unable to send command to emulator. please guide me how to corrct the error though i have added gps support while creating avd. thanx
Hi there,
ReplyDeletepls tell me how i can send a dialog box as a message asking for some permission fron the receiver...is it possible???
pls show me some light.
thnx
i am not finding “Emulation Control” tab in DDMS...plz help me to find out
ReplyDeleteReally useful, thanks! Also found this http://www.enterra-inc.com/techzone/gps-development-issues-on-android/ - quite informative,too
ReplyDeleteHow can I make this work with an AVD of 10 !!! My phone is a 2.3.4 and I need to make this work. I tryed changing the SDK version in the manifest file and also changing to a different AVD but it doesn't work... can anybody point me in the right direction? thank you
ReplyDeletehi...when i test it for 2.3.3..it comes out the error at the line of @drawable/icon" at the AndroidManifest.xml file...so may i know how to fix it?thx
ReplyDeletei already fix the error just now but now the problem is the apps i create is keep prompt to force close when i click it..
ReplyDeleteHi, this is working absolutely fine..Thanks a lot. very nice explanation. can u tel me how to get the appropiate address of tat location?? u've written u'll do it in the next project. where can i find tat?
ReplyDeleteThanks a lot for your example. Was simple and worked just great with my emulator.
ReplyDeleteThanks a lot GPS application.
ReplyDeleteWhen I am working with real device it is giving location value null.
Can you help me how to get GPS data on Real device.
My device doesn't have sim card i am using WI-FI for internet connection.
Thanks
Dharmendra
if u got any answer send to my mail santosh_kumar5671@yahoo.com
ReplyDeleteHi 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
ReplyDeleteWhat file does the LocationManger, getSystemService, etc. reside?
ReplyDeletethank u sssssssssssssssooooooooooooooo much dare
ReplyDeleteI 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
ReplyDeleteFantastic post. Here’s a tool that lets your create location-based applications such as Distance Search, Map Mashups, and Automatic Geocoding without coding http://blog.caspio.com/web_apps/create-location-based-applications-with-caspio/
ReplyDeletehi. 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?
ReplyDeletehey 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 .
ReplyDeletethis sample code not working for android 2.3.x.x (Gingerbread). So give some solution for the same.
ReplyDelete