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.onPause();
}
@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
April 16th, 2010 at 3:38 pm
Thank you, I was looking for a way to send test location data to the emulator.
[Reply]
hejp Reply:
April 16th, 2010 at 11:29 pm
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]
October 15th, 2010 at 2:06 pm
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]
November 24th, 2010 at 3:04 pm
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:
November 28th, 2010 at 8:03 pm
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]
December 17th, 2010 at 9:33 pm
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:
December 18th, 2010 at 11:50 am
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]
January 26th, 2011 at 4:02 am
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:
January 26th, 2011 at 10:58 am
In the res/layout/main.xml file, is there a TextView element with an id of textInfo?
[Reply]
elrcastor Reply:
January 26th, 2011 at 3:25 pm
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:
April 30th, 2011 at 7:40 pm
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]
January 26th, 2011 at 4:03 am
do you have an eclipse project you could post?
[Reply]
January 29th, 2011 at 9:28 am
explain in a proper way how it work and place whole code with xml also,,,,its better for the learner.
[Reply]
February 20th, 2011 at 4:56 pm
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]
March 7th, 2011 at 7:18 pm
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]
March 23rd, 2011 at 9:29 am
@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]
April 4th, 2011 at 2:42 am
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]
May 17th, 2011 at 5:44 am
[...] 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/. [...]
May 27th, 2011 at 8:33 pm
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]
May 30th, 2011 at 8:00 pm
Hello,
txtInfo = (TextView) findViewById(R.id.textInfo);
replaced by
txtInfo = new TextView(this);
-this solved mi problem with R.id!
Regards,
Mihai
[Reply]
August 9th, 2011 at 4:26 pm
Hi,
With Eclipse you need to save the main.xml after editing it before the .java picks it up.
[Reply]
August 11th, 2011 at 5:40 am
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]
October 2nd, 2011 at 11:54 pm
Thanks a lot,
I will test it
[Reply]
October 16th, 2011 at 11:20 pm
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]
GStar Reply:
November 10th, 2011 at 2:22 am
looks here
http://stackoverflow.com/questions/4883496/unable-to-override-methods-of-locationlistener-class
[Reply]
October 17th, 2011 at 8:20 pm
it is working only through the emulator
not working on the phone help please
[Reply]
November 6th, 2011 at 12:25 pm
hi,
nice tutorial, it working fine, but in my htc i am not getting any information whether i’m changing my place.
[Reply]
November 13th, 2011 at 3:11 am
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]
Raam Reply:
January 13th, 2013 at 6:09 pm
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?
[Reply]
November 28th, 2011 at 11:53 am
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]
January 30th, 2012 at 5:01 pm
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]
March 11th, 2012 at 8:57 pm
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.
[Reply]
March 18th, 2012 at 10:48 am
how to it connect??? send code please….
[Reply]
March 21st, 2012 at 6:13 am
i tried the above code.. but nothing displayed in emulator only a blank emulator with textview is displaying
[Reply]
March 21st, 2012 at 6:14 am
i tried the above code but nothing displayed in emulator
[Reply]
March 26th, 2012 at 5:59 am
[...] the example [...]
March 30th, 2012 at 6:33 am
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..!!
[Reply]
hejp Reply:
July 24th, 2012 at 5:04 pm
It’s possible because the GPS fixes are not exact just by chance the fix might be further enough away to trigger another update.
Try,
GPSManager.locationManager.requestLocationUpdates(
bestProvider,
20000,
20,
GPSManager.locationListener);
Unless accuracy is very poor 20 will probably do.
[Reply]
April 15th, 2012 at 4:02 pm
[...] 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 [...]
June 29th, 2012 at 5:29 pm
Awesome! thanks for the example. I really needed it.
[Reply]
July 6th, 2012 at 5:21 am
[...] Get the example running [...]
October 3rd, 2012 at 9:56 am
That’s quite nice tutorial, elaborated with excellence.
Cheers.
[Reply]
October 20th, 2012 at 2:30 am
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..
[Reply]
November 2nd, 2012 at 8:28 am
To all people having trouble with the null thing, its quite an easy fix:
@Override
public void onLocationChanged(Location location) {
Log.v(tag, “Location Changed”);
sb = new StringBuilder(512);
noOfFixes++;
…
to
@Override
public void onLocationChanged(Location location) {
if(location!=null){
Log.v(tag, “Location Changed”);
sb = new StringBuilder(512);
noOfFixes++;
…
[Reply]
January 8th, 2013 at 7:03 pm
[...] trying to get notifications if the status of GPS_PROVIDER changes. I found the following code here (hejp.co.uk/android/android-gps-example/), but I’m not getting notifications. Right now I’m in a building and can’t get GPS [...]
January 13th, 2013 at 6:06 pm
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?
[Reply]
hejp Reply:
February 1st, 2013 at 1:35 pm
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.
[Reply]
March 2nd, 2013 at 6:02 pm
the only thing that I can say is, you are a genius , you saved me.
LOVE YOU MAN
[Reply]
March 8th, 2013 at 8:30 pm
great article
[Reply]
April 8th, 2013 at 8:29 am
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.
[Reply]
April 9th, 2013 at 9:30 am
Thank you for your own place of duty. Thankfulness After yet again. Awesome.
[Reply]
April 19th, 2013 at 11:32 am
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.
[Reply]
April 19th, 2013 at 1:16 pm
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.
[Reply]
May 9th, 2013 at 1:51 pm
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!
[Reply]
May 18th, 2013 at 3:12 am
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.
[Reply]