Android GPS Example

April 11th, 2010

For some reason there doesn’t seem to be a clear example showing how to use GPS on Android. Here is some code I have written that listens for location changes and displays the data in a TextView. The example also shows how to open the GPS setting with code via an Intent, since sometimes the GPS will be turned off by the user.

Code

package uk.co.hejp.GPSExample;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements LocationListener {

	/* this class implements LocationListener, which listens for both
	 * changes in the location of the device and changes in the status
	 * of the GPS system.
	 * */

	static final String tag = "Main"; // for Log

	TextView txtInfo;
	LocationManager lm;
	StringBuilder sb;
	int noOfFixes = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/* get TextView to display the GPS data */
		txtInfo = (TextView) findViewById(R.id.textInfo);

		/* the location manager is the most vital part it allows access
		 * to location and GPS status services */
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
	}

	@Override
	protected void onResume() {
		/*
		 * onResume is is always called after onStart, even if the app hasn't been
		 * paused
		 *
		 * add location listener and request updates every 1000ms or 10m
		 */
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		/* GPS, as it turns out, consumes battery like crazy */
		lm.removeUpdates(this);
		super.onResume();
	}

	@Override
	public void onLocationChanged(Location location) {
		Log.v(tag, "Location Changed");

		sb = new StringBuilder(512);

		noOfFixes++;

		/* display some of the data in the TextView */

		sb.append("No. of Fixes: ");
		sb.append(noOfFixes);
		sb.append('\n');
		sb.append('\n');

		sb.append("Londitude: ");
		sb.append(location.getLongitude());
		sb.append('\n');

		sb.append("Latitude: ");
		sb.append(location.getLatitude());
		sb.append('\n');

		sb.append("Altitiude: ");
		sb.append(location.getAltitude());
		sb.append('\n');

		sb.append("Accuracy: ");
		sb.append(location.getAccuracy());
		sb.append('\n');

		sb.append("Timestamp: ");
		sb.append(location.getTime());
		sb.append('\n');

		txtInfo.setText(sb.toString());
	}

	@Override
	public void onProviderDisabled(String provider) {
		/* this is called if/when the GPS is disabled in settings */
		Log.v(tag, "Disabled");

		/* bring up the GPS settings */
		Intent intent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(intent);
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.v(tag, "Enabled");
		Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show();

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		/* This is called when the GPS status alters */
		switch (status) {
		case LocationProvider.OUT_OF_SERVICE:
			Log.v(tag, "Status Changed: Out of Service");
			Toast.makeText(this, "Status Changed: Out of Service",
					Toast.LENGTH_SHORT).show();
			break;
		case LocationProvider.TEMPORARILY_UNAVAILABLE:
			Log.v(tag, "Status Changed: Temporarily Unavailable");
			Toast.makeText(this, "Status Changed: Temporarily Unavailable",
					Toast.LENGTH_SHORT).show();
			break;
		case LocationProvider.AVAILABLE:
			Log.v(tag, "Status Changed: Available");
			Toast.makeText(this, "Status Changed: Available",
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	protected void onStop() {
		/* may as well just finish since saving the state is not important for this toy app */
		finish();
		super.onStop();
	}
}

Permissions

Of course the Android framework has security permissions to protect the user. To get the permission to use GPS add a uses-permission tag with attribute android:name set to “android.permission.ACCESS_FINE_LOCATION” to the AndroidManifest.xml document as a direct child of the manifest tag, i.e:

	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Notes

When testing this code in the emulator, you can send mock fixes by connecting to the emulator using telnet, i.e. ‘telnet localhost 5554′ and typing:

geo fix -10.223, 40.549

30 Responses to “Android GPS Example”

  1. Diane Says:

    Thank you, I was looking for a way to send test location data to the emulator.

    [Reply]

    hejp Reply:

    Yeah,

    When testing a GPS toy app I wrote a piece of Java to continuously send geo fixes, here it is:

    package uk.co.hejp;
    
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class Main {
    
    	static final int PAUSE = 4000; // ms
    	static final float START_LONGITUDE = 51, START_LATITUDE = -1.3f;
    	static final int NO_SAMPLE = 100;
    	static final float DELTA_LONGITUDE = 0.000005f, DELTA_LADITUDE = 0.000005f;
    
    	public static void main(String[] args) {
    		try {
    			Socket socket = new Socket("localhost", 5554); // usually 5554
    
    			PrintStream out = new PrintStream(socket.getOutputStream());
    			float longitude = START_LONGITUDE, latitude = START_LATITUDE;
    			String str;
    
    			for (int i = 0; i < NO_SAMPLE; i++) {
    				str = "geo fix " + latitude + " " + longitude + "\n";
    				out.print(str);
    				System.out.print(str);
    
    				Thread.sleep(PAUSE);
    
    				longitude += DELTA_LONGITUDE;
    				latitude += DELTA_LADITUDE;
    			}
    		} catch (UnknownHostException e) {
    			System.exit(-1);
    		} catch (IOException e) {
    			System.exit(-1);
    		} catch (InterruptedException e) {
    			System.exit(-1);
    		}
    
    	}
    }
    

    [Reply]

  2. Frank Says:

    Thank You for a very good example.

    I wonder if You missed to change to super.onPause() in this method:

    @Override
    protected void onPause() {
    /* GPS, as it turns out, consumes battery like crazy */
    lm.removeUpdates(this);
    super.onResume(); <==== should be super.onPause(); ???
    }

    Regards,
    Frank

    [Reply]

  3. Vaishakh Says:

    Nice work…… friend

    I am getting the accuracy of around 600-700 feets.

    Moreover my location keeps on changing within the radius of 600 fts even when I am at a static location in
    my home .Is there any way through which I can solve this problem

    [Reply]

    hejp Reply:

    Usually the accuracy is around 20m, are you using NETWORK_PROVIDER instead of GPS_PROVIDER?

    You could try setting the minDistance argument of requestLocationUpdates to 100 feet, say, so that it doesn’t update unless it’s moved substantially.

    [Reply]

  4. Erman Says:

    Hi!
    I’m new in android so i cant fix some errors in this example. At first when i run the program tv value retuns false, if i on telnet, geo fix -10.223, 40.549 i get runningtime error,
    Here is the logcat:
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): FATAL EXCEPTION: main
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): java.lang.NullPointerException
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at com.gpsler.deneme.Main.onLocationChanged(Main.java:95)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:191)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:124)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:140)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.os.Handler.dispatchMessage(Handler.java:99)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.os.Looper.loop(Looper.java:123)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.app.ActivityThread.main(ActivityThread.java:4627)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at java.lang.reflect.Method.invokeNative(Native Method)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at java.lang.reflect.Method.invoke(Method.java:521)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at dalvik.system.NativeStart.main(Native Method)

    Thanks,

    [Reply]

    hejp Reply:

    It’s difficult to tell exactly what is causing the problem but it would seem that a variable is null in onLocationChanged that shouldn’t be null.

    Go through your code inside the onLocationChanged method and find a variable that hasn’t be initialised.

    Hope that helps.

    [Reply]

  5. elrcastor Says:

    i’m useing eclipse as a dev env and it does not like the following line. any ideas?

    txtInfo = (TextView) findViewById(R.id.textInfo);

    [Reply]

    hejp Reply:

    In the res/layout/main.xml file, is there a TextView element with an id of textInfo?

    [Reply]

    elrcastor Reply:

    ok, fixed that but it did not help

    [2011-01-26 07:22:01 - main.xml] Unable to resolve id “textInfo” for attribute “id”

    [Reply]

    The Tin Man Reply:

    I was having a similar issue. I noticed that the code I had copied from a web page and pasted on main.xml looked funny. It turned out that the quotation marks (” “) did not paste as recognizeble quotation marks, so I had to delete the quotation marks that were pasted and manually input quotation marks with my keyboard. That fixed my problem.

    [Reply]

  6. elrcastor Says:

    do you have an eclipse project you could post?

    [Reply]

  7. khan Says:

    explain in a proper way how it work and place whole code with xml also,,,,its better for the learner.

    [Reply]

  8. Peter Says:

    It would help alot when you make examples to post
    the xml files as well.

    I’ve noticed that a lot of bloggers who write
    sample code leave important portions out.

    Better yet, maybe you could post the entire code (using Eclipise) in a zip file that we could download

    [Reply]

  9. Madhu Says:

    Hi, I am getting below error when it tries to execute the “lm.requestLocationUpdates” statement in onResume() CB.

    “GpsLocationProvider: native_start failed in startNavigating()”

    [Reply]

  10. Richard Says:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /* get TextView to display the GPS data */
    txtInfo = (TextView) findViewById(R.id.textInfo);

    /* the location manager is the most vital part it allows access
    * to location and GPS status services */
    lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    }

    In the above block of code, i am getting an error on the ‘id’ in findViewById(R.id.textInfo);
    What do i need to do to fix this?

    [Reply]

  11. Santana Says:

    You are a great guy! Thank you very much!
    Your code runs perfectly on my simulator, but by the other hand it did not see my Galaxy Tab GPS!
    I do not know why… It is turned on and the app Google Maps works fine!
    Anybody knows why?
    Thanks in advance.

    [Reply]

  12. Where am I? Display current GPS location | Impressive Artworx Says:

    [...] As always, you can download the source code for this tutorial. Download This tutorial is based on a blog entry by Howard Paget: http://hejp.co.uk/android/android-gps-example/. [...]

  13. OCross Says:

    I was having issues with running the example (mine is more complex than the example includes lots of other code), but it would crash on calling onresumes requestLocationUpdates. I had added the permissions in my manifest but was declaring it before the application was declared and it did not like that so once i moved it to the bottom of my manifest it then ran without crashing.

    [Reply]

  14. Mihai Says:

    Hello,
    txtInfo = (TextView) findViewById(R.id.textInfo);
    replaced by
    txtInfo = new TextView(this);

    -this solved mi problem with R.id!

    Regards,
    Mihai

    [Reply]

  15. winston Says:

    Hi,
    With Eclipse you need to save the main.xml after editing it before the .java picks it up.

    [Reply]

  16. QLeap Says:

    Many many thanks for this example. Tried it out and it worked the first time. Even taught me about the xml layouts.

    I’m very new to Android, so the textInfo compile error threw me for a while until I figured out I needed to add android:id=”@+id/textInfo” to in main.xml.

    Where to place <uses-permission… in the manifest was critical also.

    The program does quit when I rotate my phone, thought.

    A wonderful example. Thanks again!

    [Reply]

  17. Hossam Says:

    Thanks a lot,

    I will test it

    [Reply]

  18. Crash Says:

    The code isn’t working for me.

    The ‘onLocationChanged’, ‘onProviderDisabled’, ‘onProviderEnabled’ and the ‘onStatusChanged’ methods won’t let the progam run.
    It says “The method onStatusChanged(String, int, Bundle) of type GPSCheckActivity must override a superclass method” and its says I should remove the ‘@Override’ above all of those classes. am I missing something somewhere?

    THanks

    [Reply]

  19. Nader Says:

    it is working only through the emulator
    not working on the phone help please

    [Reply]

  20. Rakesh Says:

    hi,
    nice tutorial, it working fine, but in my htc i am not getting any information whether i’m changing my place.

    [Reply]

  21. krishna Says:

    hi,
    i have two codes with me.one is with gps and other is with network provider for finding the location.i want to embed second code in first one such that when gps signal is too low automatically network provider code must execute……is this possible..in which override method i have to insert……….

    thanx and waiting for reply badly….

    [Reply]

  22. Umid Says:

    Nice example, friend.
    I’ve added this to my main.xml file:

    Example is working only in emulator. On my phone it doesn’t work, even GPS Satellite and Wireless enabled.

    any suggestions?

    [Reply]

  23. Madi Says:

    works fine, but i am getting the program to “stop unexpectedly” when trying to access the phone’s location settings (when gps is turned off).

    I have a samsung galaxy s2

    thanks in advance.

    [Reply]

Leave a Reply