2012-07-01

If you are developing any location based or map application, you can make your app more smarter by finding user’s location automatically. For this you need to integrate GPS modules in your application. In this tutorial i explained how to work with GPS / Location API.



Adding Permissions in AndroidManifest.xml

Create a new Project in EClipse IDE

1. Create a new project in Eclipse File ⇒ New ⇒ Android Project and fill the required details.

To access GPS in your application you need to add required permissions in AndroidManifest.xml file. If you are getting location using GPS you need to add ACCESS_FINE_LOCATION (Which includes both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION ). Also if you are getting network-based location then you need to add INTERNET permission too.

Open your AndroidManifest.xml file and do the following changes.

Writing GPS Manager Class

2. Create a new class and name it as GPSTracker.java (I named the class as GPSTracker in this tutorial)

3. Open your GPSTracker.java and change to following. As we need to access system services extend the class from Service

4. Add the required global variables and a constructor for this class.

5. I am calling geoLocation() function in the constructor. Add a new function called geoLocation() in your GPSTracker class.

Getting user’s current location (Latitude and Longitude)

6. Add the following functions to GPSTracker.java. (These functions will return 0.00 if failed to get latitude and longitude)

Asking users to Turn On GPS (Launching System Settings)

7. If user turned off the GPS we can use ask user to enable GPS. The following code will show an Alert message asking user to turn on GPS by navigating to GPS Settings automatically.





Stop using GPS

Calling following function will stop using GPS in your application.

Final Code (GPSTracker.java)

Usage:

8. You can get user’s current location by calling simple function from GPSTracker class. Open your main activity and try the following code.

Check gps enabled or not

Getting Latitude and Longitude

Showing GPS Settings Alert Dialog

Stop using GPS

Testing your GPS App in Emulator using DDMS Tool

You can test your application in different ways. If you have real device you can directly test the application by installing your application. If you don’t have one, you can test the app using local emulator.

After starting the emulator open DDMS tool form EClipse Windows ⇒ Show Perspective ⇒ DDMS ( Also you can find it on the right corner of IDE)

After opening the DDMS tool you can find list of emulators you opened. Select the appropriate emulator. In Emulator Controls tab you can manually pass your latitude and longitude to emulator.

You can find Emulator testing in demo video of this tutorial.

Show more