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

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. */
	public void onCreate(Bundle savedInstanceState) {
		/* get TextView to display the GPS data */
		txtInfo = (TextView) findViewById(;
		/* the location manager is the most vital part it allows access 
		 * to location and GPS status services */
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
	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);
	protected void onPause() {
		/* GPS, as it turns out, consumes battery like crazy */

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

		sb = new StringBuilder(512);

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

		sb.append("No. of Fixes: ");

		sb.append("Londitude: ");

		sb.append("Latitude: ");

		sb.append("Altitiude: ");

		sb.append("Accuracy: ");

		sb.append("Timestamp: ");


	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(

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


	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",
		case LocationProvider.TEMPORARILY_UNAVAILABLE:
			Log.v(tag, "Status Changed: Temporarily Unavailable");
			Toast.makeText(this, "Status Changed: Temporarily Unavailable",
		case LocationProvider.AVAILABLE:
			Log.v(tag, "Status Changed: Available");
			Toast.makeText(this, "Status Changed: Available",

	protected void onStop() {
		/* may as well just finish since saving the state is not important for this toy app */
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

91 Responses to “Android GPS Example”

  1. Diane Says:

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


    hejp Reply:


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

    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";
    				longitude += DELTA_LONGITUDE;
    				latitude += DELTA_LADITUDE;
    		} catch (UnknownHostException e) {
    		} catch (IOException e) {
    		} catch (InterruptedException e) {


  2. Frank Says:

    Thank You for a very good example.

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

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



  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


    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.


  4. Erman Says:

    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(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport._handleMessage(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport.access$000(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.location.LocationManager$ListenerTransport$1.handleMessage(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.os.Handler.dispatchMessage(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at android.os.Looper.loop(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at
    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(
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at$
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at
    12-17 20:02:56.337: ERROR/AndroidRuntime(307): at dalvik.system.NativeStart.main(Native Method)



    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.


  5. elrcastor Says:

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

    txtInfo = (TextView) findViewById(;


    hejp Reply:

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


    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”


    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.


  6. elrcastor Says:

    do you have an eclipse project you could post?


  7. khan Says:

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


  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


  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()”


  10. Richard Says:

    public void onCreate(Bundle savedInstanceState) {

    /* get TextView to display the GPS data */
    txtInfo = (TextView) findViewById(;

    /* 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(;
    What do i need to do to fix this?


  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.


  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: [...]

  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.


  14. Mihai Says:

    txtInfo = (TextView) findViewById(;
    replaced by
    txtInfo = new TextView(this);

    -this solved mi problem with!



  15. winston Says:

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


  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!


  17. Hossam Says:

    Thanks a lot,

    I will test it


  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?



  19. Nader Says:

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


  20. Rakesh Says:

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


  21. krishna Says:

    i have two codes with 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 which override method i have to insert……….

    thanx and waiting for reply badly….


    Raam Reply:

    Did you get a solution on this – if so can you help me out? I would like use the GPS only there is good signal if not I want use network?


  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?


  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.


  24. Martin Says:

    Thanks, mate. I’m new to android developement and working on a tracking application. This example makes me go into the right direction. I have it working on HTC desire S.


  25. aneesh Says:

    how to it connect??? send code please….


  26. devi Says:

    i tried the above code.. but nothing displayed in emulator only a blank emulator with textview is displaying


  27. devi Says:

    i tried the above code but nothing displayed in emulator


  28. Week 7 – GPS | MOBI1 – VIAUC Says:

    [...] the example [...]

  29. Randi Says:

    hii,, I set the minimum time gap between 2 updates to

    `GPSManager.locationManager.requestLocationUpdates(bestProvider,20000,0, GPSManager.locationListener);`

    but my problem is when my phone is not moving, still it send different location updates to my database.

    Is there any way to overcome this problem..
    Thank you..!!


    hejp Reply:

    It’s possible because the GPS fixes are not exact just by chance the fix might be further enough away to trigger another update.



    Unless accuracy is very poor 20 will probably do.


  30. Medling with GPS | We ? Android Says:

    [...] based on some button click. So we first Implemented the example provided you too  can check it out here. We understood how it works and started reading on [...]

  31. Tyler Says:

    Awesome! thanks for the example. I really needed it.


  32. VIA SummerSchool MOB Says:

    [...] Get the example running [...]

  33. Zeeshan Says:

    That’s quite nice tutorial, elaborated with excellence.


  34. honfai Says:

    Hi, it works for me on emulator.. but when i transfer it to my phone.. it didn’t work.. nothing shown in the textInfo. (i enabled my gps provider) how can i solve this ? thanks..


  35. Isaac Gilmour Says:

    To all people having trouble with the null thing, its quite an easy fix:

    public void onLocationChanged(Location location) {
    Log.v(tag, “Location Changed”);

    sb = new StringBuilder(512);


    public void onLocationChanged(Location location) {
    Log.v(tag, “Location Changed”);

    sb = new StringBuilder(512);



  36. Androids onStatusChanged not working video Says:

    [...] trying to get notifications if the status of GPS_PROVIDER changes. I found the following code here (, but I’m not getting notifications. Right now I’m in a building and can’t get GPS [...]

  37. Raam Says:

    This is very good example but how do I fix the issue if I am under a roof where GPS is not able to fix any satellite? do you have any examples for this issue?


    hejp Reply:

    Hi Raam,

    I suppose the only thing you can do is try using the other location provider ‘network provider’. The network provider uses cell phone stations to determine the phones location, hence will work if the phone has signal but only works with phones and 3g (, etc) devices.

    You can use it as follows:

    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100f, this);

    Hope that helps. I plan to improve this post soon by including the network provider.


  38. M.Mirsamie Says:

    the only thing that I can say is, you are a genius , you saved me.


  39. Azeem Says:

    great article :)


  40. Buy Diablo 3 Gold Says:

    This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work.


  41. Bethanie Chenot Says:

    Thank you for your own place of duty. Thankfulness After yet again. Awesome.


  42. guild wars 2 gold ore areas Says:

    Link exchange is nothing else however it is just placing the other person? website link on your page at appropriate place and other person will also do similar in support of you.


  43. Lyndon Says:

    Tobacco has not simply been connected to low birth weight but can be considered a detrimental agent show them into one’s body during the crucial developmental stages from the fetus, especially during the very first trimester of pregnancy. Article Source: can find helpful information about. If you’re pregnant
    and also have tinnitus, talk to your doctor about
    how you can treat it naturally. As the women have to put additional
    weight during pregnancy, they started exploring options to shred the additional pounds and obtain back
    their old figure. Remember though, the last thing you must be stopping is nutrients essential for growth and development.


  44. Kellee Says:

    Amazing! Thiѕ blοg loοks just
    liκe my оld one! It’s on a completely different topic but it has pretty much the same layout and design. Excellent choice of colors!


  45. tanie taxi kraków Says:

    Thank you for another magnificent post. Where else may anyone get that type of
    information in such a perfect way of writing? I’ve a presentation next week, and I am at the look for such information.


  46. repetitive stress injuries Says:

    Greetings! Very helpful advice in this particular article!
    It’s the little changes that will make the largest changes.
    Thanks a lot for sharing!


  47. Sammie Says:

    Hi, Neat post. There’s a problem with your website in internet explorer, would test this? IE still is the market leader and a good portion of people will miss your great writing due to this problem.


  48. asd Says:

    What you posted made a ton of sense. However, what about
    this? what if you composed a catchier post title? I am
    not saying your content is not solid., but what if you added a
    headline that grabbed a person’s attention? I mean HEJP’s Blog ? Blog Archive
    ? Android GPS Example is a little vanilla.
    You should glance at Yahoo’s home page and note how they create post titles to get viewers interested. You might add a related video or a related pic or two to get people excited about what you’ve written.
    Just my opinion, it would bring your website a little livelier.


  49. haarausfall Says:

    It’s remarkable in support of me to have a site, which is
    beneficial for my knowledge. thanks admin

    Feel free to visit my website – haarausfall


  50. touseef Says:

    i didnt get any location :( but my code is running correctly no error i phase but in text view i didnt get any thing :( nor a toast message :(


  51. ?????? Says:

    Thank you a lot for sharing this with all folks
    you really recognise what you’re speaking about! Bookmarked.
    Kindly also discuss with my web site =).
    We will have a hyperlink trade agreement among us


  52. Cheap Cuban Cigars for Sale Says:

    We are a group of volunteers and opening a new scheme in our community.
    Your website offered us with valuable information to work on.
    You have done an impressive job and our entire community will be thankful
    to you.

    my web page :: Cheap Cuban Cigars for Sale


  53. Says:

    Hi, yup this pardagraph is really good and I have learned lot of things
    from it about blogging. thanks.


  54. herbs for kids Says:

    It’s awesome for me to have a website, which is valuable in favor
    of my knowledge. thanks admin


  55. Says:

    wonderful submit, very informative. I’m wondering why
    the other specialists of this sector do not realize this.
    You must continue your writing. I’m sure, youu have a great
    readers’ base already!

    my web blog … Brett Cravaliat;,


  56. Free Eshop Card Generator Says:

    Hola! I’ve been following your site for some time now and finally
    got the courage to go ahead and give you a shout
    out from Humble Tx! Just wanted to say keep up the excellent job!


  57. Gavin Says:

    Je prends la peine d’écrire ce com uniquement pour remercier le webmaster


  58. clinical depression definition Says:

    Goodd blog you’ve gott here.. It’s hard to find good qualit writing like yours nowadays.

    I really appreciate peolple like you! Take care!!


  59. article directory submitter Says:

    Follow a healthy diet plan packed with vegetables and fruit.
    Limit wine to one glass a day or risk halting your body’s release of its own antidiuretic hormone, causing dehydration of your
    skin. Utilize a product specifically designed for resting to combat this challenge.


  60. beach cover up Says:

    Just like other clothes, swimwear too is subject to wear and tear.
    It is a soft and lightweight fabric, produced in a tricot factory, which makes the day at the
    beach all the more enjoyable as well as comfortable. Some of
    the popular ranges incorporate , Arabella, Celia, Frankie, Carly, Cindy, Deco,
    Mimi, Millie, Pippa, Pollyanna, Retro, Rio, Saffy, Zara.


  61. Says:

    This website definitely has all of the information and facts I
    wanted concerning this subject and didn’t know who
    to ask.


  62. Gregorio Says:

    Asking questions are really fastidious thing if you are not
    understanding anything fully, except this
    paragraph gives fastidious understanding yet.


  63. Says:

    I don’t even know how I ended up here, but I
    thought this post was good. I don’t know who you are
    but certainly you are going to a famous blogger if you aren’t already ;) Cheers!


  64. Google Says:

    No one routes for the evil villan who’s run off with the hero’s beau,
    same applies to a site that’s been stuck in Google‘s naughty corner.

    This will allow you to answer only those calls that come in on your forwarded toll free number and
    route other calls to different locations. There are other ways to improve
    your ranking in Googlemaps, the purpose of this blog post is not to tell you EVERYTHING Frederick Web
    Promotions can do to improve your ranking, the purpose of
    this particular blog post is to:.


  65. laptop second hand Says:

    I’m gone to convey my little brother, that he should also pay a visit this web site on regular basis to
    obtain updated from newest news.


  66. electronic cigarette shops in ireland Says:

    When someone writes an paragraph he/she keeps the plan of a user in his/her brain that
    how a user can be aware of it. Therefore that’s why
    this paragraph is amazing. Thanks!


  67. toy drone helicopter for sale Says:

    Great blog! Do you have any hints for aspiring writers? I’m planning to start my
    own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a
    paid option? There are so many choices out there that I’m totally overwhelmed ..
    Any recommendations? Bless you!


  68. website Says:

    Thanks for finally writing about > HEJP’s Blog ? Blog Archive ? Android GPS Example < Liked it!


  69. auto parts in lekki Says:

    Asking questions are genuinely good thing if you are
    not understanding something fully, except this paragraph presents nice understanding yet.


  70. Everette Says:

    The resulting fibrous tissue leads to a bend to produce during erection that is certainly painful
    and might make intercourse hard or impossible. Type the suitable keywords,
    for example, when you are searching information related to “Male Enhancement” or “Male
    Penis Enhancement” then your keywords can be “Male Enhancement Options” or “Male Penis Enhancement Options”.

    Male – Extra is sure to tick all of your boxes and will certainly prove to be the no.


  71. Lou Says:

    Finally i quit my regular job, now i earn a lot of money on-line you should try too, just search in google
    - slabs roulette system


  72. Says:

    Enhance the effect of an elliptical machine as a 24hr fitness
    trainer, by deciding upon a machine that also capabilities handlebars for a incredibly effective
    total human body exercise. One has to wonder how Kenya’s fitness DVD has become such a huge hit in Japan. Their club provides a
    huge state of the art equipment, saunas,
    masseurs, nutritionists, beauty therapists and the best personal training programs which will help
    you to get the best out of them.


  73. market your video Says:

    I know this if off topic but I’m looking into starting my own weblog and was
    wondering what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% certain. Any tips or advice would be greatly appreciated.


  74. forthcoming books Says:

    I’m amazed, I have to admit. Seldom do I come across a blog that’s
    both equally educative and amusing, and without
    a doubt, you’ve hit the nail on the head. The issue is something which
    too few men and women are speaking intelligently about.
    I’m very happy I stumbled across this in my hunt
    for something relating to this.


  75. clipped coupons Says:

    Excellent blog you’ve got here.. It’s difficult to find excellent writing like yours
    these days. I honestly appreciate individuals like
    you! Take care!!


  76. fractured elbow Says:

    Every weekend i used to visit this web site, because i wish for enjoyment, for the
    reason that this this web site conations in fact pleasant funny
    data too.


  77. fate brewing Says:

    Helpful info. Lucky me I discovered your site unintentionally, and I am surprised why this
    accident didn’t came about in advance! I bookmarked it.


  78. Valencia Says:

    Thanks a lot for sharing this with all people you actually recognise what you’re talking about! Bookmarked. Please additionally seek advice from my website =). We will have a link change contract between us


  79. Adolph Says:

    An interesting discussion is worth comment. There’s no doubt that that you ought to write more about this topic, it may not be a taboo matter but generally folks don’t speak about these subjects. To the next! Best wishes!!


  80. Erick Says:

    You can definitely see your enthusiasm in the article you write. The sector hopes for more passionate writers like you who aren’t afraid to say how they believe. All the time follow your heart.


  81. best green teas Says:

    For the 3rd overload version Sort method, it is useful when we only
    need to sort a range of items in an Array – List. I possess all the skills required to be a part of this program.
    Common examples are the one which a writer personally experiences and therefore, incorporate in the illustration essay but it should
    be pertinent to the topic of the illustration essay.


Leave a Reply