This article will show you how to programmatically access the data returned by your built-in GPS receiver.
In Android, location-based services are provided by the LocationManager class located in the android.location package.
Using the LocationManager class, we can obtain periodic updates of the device's geographical locations as well as fire an intent when it enters the proximity of a certain location.
1. Obtain a reference to the LocationManager class using the getSystemService() method.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
2. Create a LocationListener Class for notify the location changes.
Our MyLocationListener class should implements the LocationListener abstract class. There are four methods that you need to override in this implementation:
* onLocationChanged(Location location): This method is called when the location has changed.
* onProviderDisabled(String provider): This method is called when the provider is disabled by the user.
* onProviderEnabled(String provider): This method is called when the provider is enabled by the user.
* onStatusChanged(String provider, int status, Bundle extras): This method is called when the provider status changes.
3. To be notified whenever there is a change in location, you need to register for a request for changes in locations so that your program can be notified periodically. This is done via the requestLocationUpdates() method (see Listing 1).
This method takes in four parameters:
* provider: The name of the provider with which you register
* minTime: The minimum time interval for notifications, in milliseconds.
* minDistance: The minimum distance interval for notifications, in meters.
* listener: An object whose onLocationChanged() method will be called for each location update.
4. Set the following User-Permission in androidmanifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
Sample Code :
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
In Android, location-based services are provided by the LocationManager class located in the android.location package.
Using the LocationManager class, we can obtain periodic updates of the device's geographical locations as well as fire an intent when it enters the proximity of a certain location.
1. Obtain a reference to the LocationManager class using the getSystemService() method.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
2. Create a LocationListener Class for notify the location changes.
Our MyLocationListener class should implements the LocationListener abstract class. There are four methods that you need to override in this implementation:
* onLocationChanged(Location location): This method is called when the location has changed.
* onProviderDisabled(String provider): This method is called when the provider is disabled by the user.
* onProviderEnabled(String provider): This method is called when the provider is enabled by the user.
* onStatusChanged(String provider, int status, Bundle extras): This method is called when the provider status changes.
3. To be notified whenever there is a change in location, you need to register for a request for changes in locations so that your program can be notified periodically. This is done via the requestLocationUpdates() method (see Listing 1).
This method takes in four parameters:
* provider: The name of the provider with which you register
* minTime: The minimum time interval for notifications, in milliseconds.
* minDistance: The minimum distance interval for notifications, in meters.
* listener: An object whose onLocationChanged() method will be called for each location update.
4. Set the following User-Permission in androidmanifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
Sample Code :
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
is this code working..............?
ReplyDeleteYES, I tried and it works.
ReplyDeleteextremly simple & useful.
ReplyDeleteThanks.
It is not working..! while run the app it will show Application clod unexpectly
ReplyDeleteit's not working.while running it shows application has stopped unexpectedly.
ReplyDeleteYou must add these permissions in Android manifest:
ReplyDeleteACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
ACCESS_LOCATION_EXTRA_COMMANDS
ACCESS_MOCK_LOCATION
CONTROL_LOCATION_UPDATES
This is very useful for me.I have 1 doubt i will give mobile number how to find user location.pls reply for me.
ReplyDeletegreat job, thanks
ReplyDeleteHI this is not working open empty screen ..... please tell me the code to run the appln correctly......
ReplyDeleteThis code is great, and can be found in a lot of places online, but I've had the hardest time trying to find a simple tutorial that teaches how to develop an activity to compute and display SPEED.
ReplyDeleteSorry, the code is not working.
ReplyDeleteWorked for me on my Verizon Droid running 2.2.2
ReplyDeletesorry not working ... can you please mention the version on which this should be run
ReplyDeletecan you please provide the main.xml containts
ReplyDeleteNot Working
ReplyDeleteNot Working
ReplyDeletehey guys this is working. Are u guys waiting for the sattelite to get a lock???
ReplyDeletefor those who didn't get any thing on there screen:
ReplyDelete1 goto terminal
2 telnet localhost 5554 //this is your emulator name
3 geo fix 50 50 //press enter and see your emulator screen
hi brither above code is not working iam fresher please where i have to change
ReplyDeleteFor those who said that this code is not working:
ReplyDeletethere are 2 options:
1 – We can run our application in the Phone.
2 – Run the application with the simulator.
For the second case, to simulate a location update we need to connect to the simulator by telnet, and do the fallowing:
telnet localhost 5554(your device name)
geo fix 30 28(30 28 are latitude and longitude)
Hi - I have connected to Telnet in my win 7 like this: http://www.itdoescompute.com/2009/10/29/how-to-enable-telnet-in-windows-7/
DeleteWhat to do thereafter? As Varun Bhardwaj writes, do I have to go to the windows command prompt/terminal (or at the Telnet.exe prompt?) and write: "telnet localhost 5554" only? .... -> and under which directory do I have to do this? Cause it doesn't work just writing it, as the prompt just answers me: "Could not establish connection to host at 5554: The connection was not established".
I am coding in Eclipse, and I am therefore trying the code above in there with the following permission altering at the bottom AndroidManifest.xml: "
"
Can/should I open a terminal window inside Eclipse? ... and/or what do I do wrong? Thx on beforehand /br Thomas Due, DK
This comment has been removed by the author.
Delete(nb: the text formatter excluded some of my txt above - here it is in a non-xml way (hopefully))
Deleteuses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" uses-permission android:name="CONTROL_LOCATION_UPDATES"
Hi! I have also tried this but it doesn't work for me either. I have send the gps from cmd and also from eclipse but still won't work. I have also set all the permissions. My app just won't even start. As soon as it is launched it says that has stopped unexpectedly. what should I do? I have checked all I knew that might be the problem. When I try to debug it, I have set the breakpoint at the first line from OnCreate and it stops there saying Source not found! Can anyone help me? Thank you!
ReplyDeleteI have solved my problem...in case anyone with the same problem sees this. You have to change the virtual device machine to a lower level of Android(to level 8 for example). Good luck!
ReplyDeleteIs it possible to emulate the GPS device by the emulator to find the users location
ReplyDeletegr88:) working fine.
ReplyDeleteHi this code is not working its coming blank screen i added this permissions also
ReplyDeleteACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
ACCESS_LOCATION_EXTRA_COMMANDS
ACCESS_MOCK_LOCATION
CONTROL_LOCATION_UPDATES.
but not working please any one help me it is very use full to me please ...........................
Eclipse wants to remove @Override annotations... is it good ? I dont think so.
ReplyDelete@above:
ReplyDeleteyes eclipse threw the same error for me too, but it worked without the override annotation also! :)
can any knows how to find nearest location from current location
ReplyDeleteplz help me..
its not working................................
ReplyDeletedoes not work!
ReplyDeleteMany thanks. Your code snippet works perfectly.
ReplyDeleteToast.makeText(MainActivity.this,
ReplyDeletelocation.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
I have an error in "MainActivity.this":
No enclosing instance of the type MainActivity is accessible in scope.
Anybody can help?
Example worked for me. I am planning to use that Location object and show that on Map using GeoPoint object with OverlayItem object to overlay point on the Google Map. It does not work for me yet or it works but location shown on map is not accurate so working on it. Location object Latitude and Longitude coordinates are in double so could anyone show that using GeoPoint which takes coordinates in int format.
ReplyDeleteAnyone else had a luck doing that?
Nice tutorial..
ReplyDeletei am gettin error in two following lines
ReplyDelete1)LocationListener ll = new mylocationlistener();
and also in this line
2)private class mylocationlistener implements LocationListener {
This is for those who say it does not works on real device, i experienced the same problem on my samsung Galaxy 5 i got my problem solved bcoz of changing GPS_PROVIDER as NETWORK_PROVIDER. I got the solution "Network Provider" determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
ReplyDeleteBut "GPS Provider" determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
This is the problem with device, our device doesnot supports gps without internet it only uses location provider.
undercoverultimatecollections.blogspot.com
whats the purpose of just getting coordinates?how can we get location address by using these?
DeleteThank you!
ReplyDeleteEclipse insisted on removing @Override to compile
Removing the following lines got it working on the device:
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Hi:
ReplyDeleteI am looking for an HTML code snippet that includes the JAVA routine to acquire lat and long and pass it to my HTML code.
I have never used JAVA and appear to be forced here cause the JavaScript routines that I have used to get lat and long don't work on Android 4, but do work on an iPhone and on earlier Android versions. I am assuming that these JAVA routines will work on Android 4.
Thanks for the tutorial worked well for me :)
ReplyDeleteIf people are having trouble, try including the following line below the other request in onCreate. This worked for me.
lm.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, ll );
This comment has been removed by the author.
DeleteThanks ! after add this in onCreate: lm.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, ll ); it work nice.!Greate.
Deleteworked well! ;)
ReplyDeleteGreat work, Good luck.
ReplyDeleteIf nothing is seen on the screen, Please do the following (In Windows)
Step 1: Open command line (Run -> cmd)
Step 2: Type telnet localhost 5554
Step 3: If telnet is installed properly Android console will be shown
Step 4: Type geo fix (Example: geo fix 40 40)
At last look at the emulator, You will be shown a toast with latitude and longtitude
Hope this makes the invisible into visible
Hello
ReplyDeleteWE make android application Project but when we run the codes the map does not working we do not the see map we see White screen.how solved this problem,can you helmp me
this is the only code that worked for me. THANKS! I tried all the examples and tutorials on the internet but finally it works. so short, so complete, so wow... ;)
ReplyDeleteplease show main.xml
ReplyDeleteit asks for self permission check and then when you run it application gets crashed
ReplyDeletehere it asks for self permission lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
Good work.but i can't get full details.anyway thanks for sharing and try to this blog Phone Number Search.It's really helpful for you thanks for sharing...
ReplyDeleteI want to find nearest petrol pump from my location in python programming
ReplyDeleteWohh exactly what I was searching for, appreciate it for posting.
ReplyDeleteFeel free to surf to my weblog :: 풀싸롱
Hello, I am one of the most impressed people in your article. 우리카지노 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.
ReplyDeleteHow can you think of this? I thought about this, but I couldn't solve it as well as you.샌즈카지노I am so amazing and cool you are. I think you will help me. I hope you can help me.
ReplyDeleteI have been looking for articles on these topics for a long time. 카지노사이트 I don't know how grateful you are for posting on this topic. Thank you for the numerous articles on this site, I will subscribe to those links in my bookmarks and visit them often. Have a nice day
ReplyDelete