Sunday, 12 September 2010

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 :



56 comments:

  1. How to keep the location record and draw the lines in the map for those location?

    How I want to review what I had been to?

    Something likes Route Tracking!

    ReplyDelete
  2. hi

    i tried to execute your code bu im getting a lot of errors.
    the string.format() command has errors.
    is the downloadable code fully correct?

    ReplyDelete
  3. @shoiks
    Hi, 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.

    ReplyDelete
  4. HI,
    How to locate using maps,i mean Something likes Route Tracking!

    ReplyDelete
  5. 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 ?

    ReplyDelete
  6. hi
    i 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'

    ReplyDelete
  7. Cool,

    try 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

    ReplyDelete
  8. @ allan

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

    ReplyDelete
  9. @ abdalla000

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

    ReplyDelete
  10. Great tutorial!!! Thanks.

    I 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

    ReplyDelete
  11. Hi Jay-K,

    Really 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

    ReplyDelete
  12. I have a problem when sending mock data to the app.

    It 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?

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

    ReplyDelete
  14. thanx 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

    ReplyDelete
  15. HI,

    This code help me a lot.Thanks .

    ReplyDelete
  16. hey when i run the same on actual device it returns me null as location object, how to fix it?
    As i am completely new bie for and

    ReplyDelete
  17. When I run on android phone, nothing happen except button(its can press)

    ReplyDelete
  18. hey 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
  19. @yoo_sousa,appleboy
    Please 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.

    ReplyDelete
  20. this was very help ful .thanks a lot!!
    d 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

    ReplyDelete
  21. Hi hrishi,

    I 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

    ReplyDelete
  22. Hi Fabrizio,
    Thanks 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??

    ReplyDelete
  23. Hi again hrishi,

    Android 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

    ReplyDelete
  24. Hi am trying last tow days i am geting location value is null only.... pls tell the correct ans...

    ReplyDelete
  25. I 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?

    ReplyDelete
  26. thnx this is really helpful

    ReplyDelete
  27. Your are the best. Thumbs up for ya.

    ReplyDelete
  28. hai
    I 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.............

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

    ReplyDelete
  30. I 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....

    ReplyDelete
  31. hi i am trying to run. but no response coming on Retrieve Location button click????????????

    ReplyDelete
  32. This is not working for me in real device

    ReplyDelete
  33. Hi. Great Tutorial. Helps me a lot. Looking forward to trying some more from javacodegeeks.

    ReplyDelete
  34. had some of the issues esp the string format one and with @overide
    For 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).

    ReplyDelete
  35. 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?

    Thaks a lot.

    ReplyDelete
  36. Hi there.
    wht is difference Google API level 13 and level 4.
    Is level 13 more advanced than level 3 ???
    Or are these different in there functionalities??

    ReplyDelete
  37. Hi there,
    thanx 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

    ReplyDelete
  38. Hi there,
    pls 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

    ReplyDelete
  39. i am not finding “Emulation Control” tab in DDMS...plz help me to find out

    ReplyDelete
  40. Really useful, thanks! Also found this http://www.enterra-inc.com/techzone/gps-development-issues-on-android/ - quite informative,too

    ReplyDelete
  41. How 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

    ReplyDelete
  42. hi...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

    ReplyDelete
  43. i 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..

    ReplyDelete
  44. Hi, 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?

    ReplyDelete
  45. Thanks a lot for your example. Was simple and worked just great with my emulator.

    ReplyDelete
  46. Thanks a lot GPS application.
    When 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

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

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

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

    ReplyDelete
  50. thank u sssssssssssssssooooooooooooooo much dare

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

    ReplyDelete
  52. Fantastic 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/

    ReplyDelete
  53. 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?

    ReplyDelete
  54. Bhuvan Chandra9 April 2012 12:46

    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 . 

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

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...