Thursday, April 15, 2010

Find Current Location in Android - GPS Sample

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) {
    }
    }
}


48 comments:

  1. is this code working..............?

    ReplyDelete
  2. It is not working..! while run the app it will show Application clod unexpectly

    ReplyDelete
  3. it's not working.while running it shows application has stopped unexpectedly.

    ReplyDelete
  4. You must add these permissions in Android manifest:

    ACCESS_COARSE_LOCATION
    ACCESS_FINE_LOCATION
    ACCESS_LOCATION_EXTRA_COMMANDS
    ACCESS_MOCK_LOCATION
    CONTROL_LOCATION_UPDATES

    ReplyDelete
  5. This is very useful for me.I have 1 doubt i will give mobile number how to find user location.pls reply for me.

    ReplyDelete
  6. HI this is not working open empty screen ..... please tell me the code to run the appln correctly......

    ReplyDelete
  7. This 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.

    ReplyDelete
  8. Sorry, the code is not working.

    ReplyDelete
  9. Worked for me on my Verizon Droid running 2.2.2

    ReplyDelete
  10. sorry not working ... can you please mention the version on which this should be run

    ReplyDelete
  11. can you please provide the main.xml containts

    ReplyDelete
  12. hey guys this is working. Are u guys waiting for the sattelite to get a lock???

    ReplyDelete
  13. for those who didn't get any thing on there screen:
    1 goto terminal
    2 telnet localhost 5554 //this is your emulator name
    3 geo fix 50 50 //press enter and see your emulator screen

    ReplyDelete
  14. hi brither above code is not working iam fresher please where i have to change

    ReplyDelete
  15. For those who said that this code is not working:
    there 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)

    ReplyDelete
    Replies
    1. 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/

      What 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

      Delete
    2. This comment has been removed by the author.

      Delete
    3. (nb: the text formatter excluded some of my txt above - here it is in a non-xml way (hopefully))

      uses-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"

      Delete
  16. 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!

    ReplyDelete
  17. I 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!

    ReplyDelete
  18. Is it possible to emulate the GPS device by the emulator to find the users location

    ReplyDelete
  19. Hi this code is not working its coming blank screen i added this permissions also
    ACCESS_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 ...........................

    ReplyDelete
  20. Eclipse wants to remove @Override annotations... is it good ? I dont think so.

    ReplyDelete
  21. @above:
    yes eclipse threw the same error for me too, but it worked without the override annotation also! :)

    ReplyDelete
  22. can any knows how to find nearest location from current location
    plz help me..

    ReplyDelete
  23. its not working................................

    ReplyDelete
  24. Many thanks. Your code snippet works perfectly.

    ReplyDelete
  25. Toast.makeText(MainActivity.this,
    location.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?

    ReplyDelete
  26. 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.
    Anyone else had a luck doing that?

    ReplyDelete
  27. i am gettin error in two following lines
    1)LocationListener ll = new mylocationlistener();
    and also in this line
    2)private class mylocationlistener implements LocationListener {

    ReplyDelete
  28. 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.

    But "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

    ReplyDelete
    Replies
    1. whats the purpose of just getting coordinates?how can we get location address by using these?

      Delete
  29. Thank you!

    Eclipse 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() + "");

    ReplyDelete
  30. Hi:

    I 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.

    ReplyDelete
  31. Congratulations! This is the great things. Thanks to giving the time to share such a nice information.
    Location Solutions

    ReplyDelete
  32. Thanks for the tutorial worked well for me :)

    If 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 );

    ReplyDelete
  33. Great work, Good luck.

    If 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

    ReplyDelete
  34. Hello
    WE 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

    ReplyDelete
  35. 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... ;)

    ReplyDelete