Get Current Location in Android

Last modified on October 24th, 2014 by Joe.

This android tutorial is to help learn location based service in android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve peoples daily problem. For developing location aware application in android, it needs location providers. There are two types of location providers,

  1. GPS Location Provider
  2. Network Location Provider

currentLocation

Any one of the above providers is enough to get current location of the user or user’s device. But, it is recommended to use both providers as they both have different advantages. Because, GPS provider will take time to get location at indoor area. And, the Network Location Provider will not get location when the network connectivity is poor.

Network Location Provider vs GPS Location Provider

Steps to get location in Android

  1. Provide permissions in manifest file for receiving location update
  2. Create LocationManager instance as reference to the location service
  3. Request location from LocationManager
  4. Receive location update from LocationListener on change of location

NetworkProvider

Provide permissions for receiving location update

To access current location information through location providers, we need to set permissions with android manifest file.

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

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.

Create LocationManager instance as reference to the location service

For any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using getSystemService() method. This reference will be added with the newly created LocationManager instance as follows.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Request current location from LocationManager

After creating the location service reference, location updates are requested using requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance and the LocationListener object over which the location to be updated.

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

Receive location update from LocationListener on change of location

LocationListener will be notified based on the distance interval specified or the number seconds.

Sample Android App: Current Location Finder

This example provides current location update using GPS provider. Entire Android app code is as follows,

package com.javapapers.android.geolocationfinder;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import android.util.Log;

public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude; 
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

XML files for layout and android manifest are as shown below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.geolocationfinder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17"        />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >
        <activity
            android:name="com.javapapers.android.geolocationfinder.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Android Output

AndroidLocationOutput

Note: If you are running this Android app with emulator, you need to send the latitude and longitude explicitly for the emulator.

How to send latitude and longitude to android emulator

Comments on "Get Current Location in Android"

  1. ANUJ says:

    nice tutorial sir………..

  2. s.selvakumar says:

    Hi Sir,

    I am a java developer but not a Android developer. I would like to develop one simple contact save application in android. Could you please publish step by step development procedure for contact book application with sqlite db interaction.

    Thanks,
    s.selvakumar

  3. Naiyer azam says:

    What are all requirement to run anroid applicatio

  4. Ravi says:

    Very nice article. Steps are nicely explained. Thank you Sir

  5. Durai says:

    Hi,
    How can i scan barcodes in android application!

  6. prasannakumar says:

    yes u can use barcode scan u will find source code for barcode scan check it in github repository once i used zxing(a barcode scanner Engine)

  7. […] we studied about how to get current geographic location using an android application. That Android app will return latitude and longitude pair to represent current location. Instead of […]

  8. Sachchit says:

    Does this app need any type of internet ???

  9. Anonymous says:

    I run the above code.but only hello world is displayed.no location data.Please specify the code for activity main.xml to display the location

  10. Celso says:

    Simple and Efficient..

  11. nice tutorial….

  12. Anonymous says:

    i am new to android ,i tried the same but when i run it shows me “unfortunately app has stopped working” please help me fix this.

  13. Archie Jain says:

    Very helpful!

  14. parag says:

    Very nice tutorial.Please tell me how can we use these coordinates to locate this position in the map .thank you

  15. Joe says:

    First you need to display the map fragment (https://javapapers.com/android/show-map-in-android/), then you need to tile these coordinates on top of it by using location service / activity.

    I will post a tutorial for this exact topic very soon.

  16. Anonymous says:

    hi..!!!
    its working fine when im using emulator,but it is showing nothing when im uing it in my phone..!!
    just hello world is outputed on the screen..!!

  17. Arefin says:

    Hi,
    How can i get output in phone instead of emulator because it works in emulator.

  18. jitendra singh yadav says:

    i am new to android ,i tried the same but when i run it shows me “unfortunately app has stopped working” please help me fix this

  19. Tanuja says:

    thanks alot for helping by this tutorial..
    can u tell me hopw to find the direction and KMS using android google maps

  20. Saket says:

    I’m new to android as well and was getting the same error. What solved it was that I tried it on device and not the emulator. The emulator kept giving me error even after sending values through DDMS.

    second mistake i made was i changed the name of the package and forgot to change the names in manifest. Just make sure you are not doing the same.

  21. Roopesh says:

    Worked instantly.. Thanks for the tutorial..

  22. Narendra says:

    how to get date and time from internet in android

  23. Yajneshwar Mandal says:

    Very good tutorial …

  24. kumar says:

    Hi,
    The latitude and longitude is shown, can you add the direction to the latitude and longitude like

    Latitude 37.42 North
    Longitude 122.56 East

    Because i needed this for astrology app

  25. Arindam says:

    Thanks Joe,for the post and for GPS Location Provider is works perfectly.

  26. shubham says:

    how to develop a music player stand alone application in java……?

  27. Anonymous says:

    very good tutorial…thanks sir

  28. divya says:

    its working fine in emulator kindly intimate how to display in tab

  29. Harshal says:

    Have you posted any tutorial for network based on network location service yet?

    Please give URL,

    Thank You

  30. pankaj says:

    very simple dear
    1-install eclipse.
    2-After debug the program u will the .apk file
    inside Bin folder.
    3-Copy the .apk file and put inside ur mobile and run it…

  31. Anonymous says:

    dear Joe when i install apk file in Phone only
    hello world message is display not lat n long find

    i an new in android apps please help and suggest how to call .NET web service in this with post and get method

  32. Ramasamy says:

    I think you are testing code by emulator. If yes, you need to set lattitude and longtitude manually. Its also said by author at the end of this tutorial. Please look at that and then try. Its running good for me.

  33. Indra says:

    great job amazing work simple easy yet effective

  34. karthik says:

    Nice one.
    But This one is not working inside the room.we need the display the current location using network provider.

  35. leo says:

    Thanks, great tutorial, best i found and works like a charm.
    Can you publish one explaning GoogleMaps ?

    Regards

    L

  36. Prasoon says:

    hi , i manually added langitute and logitute .but nothing showing on my emulator..
    it says only
    latitute=Location not available
    longitude=Location not available

  37. Dilip says:

    This code is not working inside the room.we need the display the current location using network provider.

  38. Bryn says:

    Great tutorial. I keep having the same problem with certain apps I write – in that they work on the emulator, but give an error on my cell phone.

    App starts up then suddenly gives the message “Unfortunately, GPSapp has stopped”

    Any ideas would be greatly appreciated

    Galaxy S4 cell, 4.2.2

  39. Bryn says:

    Apologies – I see this question has been raised a few times before. I have tried the suggestions above (eg make sure package name is same in program and manifest etc) but still no joy. Thanks Bryn

  40. Joe says:

    Bryn,

    There can be numerous reasons to a crash. Best way to find the reason is to get the LogCat logs when it crashes. Plug the phone in USB and set it as target device. Then launch the app in phone and you can get the logs on this error.

  41. grimes says:

    all are incredible !

  42. Jan Zitniak says:

    For anyone who shows “Hello World” on the mobile phone instead current location change MainActivity.java to following:

    package com.javapapers.android.geolocationfinder;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.widget.TextView;

    import android.util.Log;

    public class MainActivity extends Activity implements LocationListener {
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    protected LocationManager locationManager;
    protected Context context;
    protected boolean gps_enabled, network_enabled;
    TextView txtLat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtLat = (TextView) findViewById(R.id.textview1);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // getting GPS status
    gps_enabled = locationManager
    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // getting network status
    network_enabled = locationManager
    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (gps_enabled) {
    locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    } else if (network_enabled) {
    locationManager.requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    };
    }

    @Override
    public void onLocationChanged(Location location) {
    txtLat = (TextView) findViewById(R.id.textview1);
    txtLat.setText(“Latitude:” + location.getLatitude() + “, Longitude:”
    + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
    Log.d(“Latitude”, “disable”);
    }

    @Override
    public void onProviderEnabled(String provider) {
    Log.d(“Latitude”, “enable”);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.d(“Latitude”, “status”);
    }
    }

  43. Shashank Dixit says:

    In my code, onLocationChanged() method is not getting called while I am running my app on mobile. What may be the reason behind it?

  44. Kannan says:

    How to send latitude and longitude to android emulator

    Open DDMS perspective in Eclipse (Window -> Open Perspective)
    Select your emulator device
    Select the tab named emulator control
    In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.

    For this steps we simple load a .kml file to emulator that will take a automatically from the LOCATION CONTOLS…

  45. Edith says:

    Thanks for a nice tutorial.Kindly help me on how to serve the obtained coordinates(latitudes&longitudes) to MySQL database.

  46. Isuru Chathuranga says:

    Thank you sir…
    this is very important to me. Pleas carry on your tutorials ahead.

  47. Khalid Sweeseh says:

    I have seen some applications being able to retrieve the VLR Global title , something like the Node Number you are latched on , for example in Jordan it will be something like 96279123456 , but from the API i am not able to get to that level , any idea how could that have been done ?

  48. Edith says:

    Can anyone please help me on automatic storage of the obtained coordinates (latitude &longitude…from this tutorial)in mySQL database, this should be done without requiring the phone user to press a send button.
    May God bless you for your kind assistance.
    Happy coding!!

  49. Edith says:

    Friends,is there no one who can give a hint on this??? Plz your assistance or some links/books to refer to will help me a lot.

  50. sachin thawari says:

    Hi Sir

    I want to find my friend location trough googlemap
    So what kind of permission i have to use in my manifest file ,is this possible??

    i am working on one friend Find locater .
    reply

  51. Ashik says:

    Sir this code running well in emulator but not in phone device and itz by default shows hello world.. how can i fix it?and as like many people are geeting same problem.. pls gv us proper solution.

  52. Deepa says:

    Its is really awesome tutorial Thank You :-)

  53. Vellaiyappan says:

    Sir,
    i am using GPS Location find in my application and how to store in sqlite database so i am confuesd please help me sir.

    i need source code

  54. […] said all the above, I just noticed that I have written an Android GPS tutorial already. Though I feel like a buffoon, somehow I have to manage now. Its okay, it will do no harm […]

  55. Tom says:

    Thank you

  56. Sreejith says:

    Thank you sir..
    it working well..

  57. pratahm says:

    gives me error saying “textview1 cannot be resolved or is not a field”.
    thanks.

  58. soheil says:

    hello
    nice tutorial
    you put all your code but why you did not put android project here? thanks alot

  59. robin says:

    Hi,
    I want to put a marker to the current location and keep updating the marker to new position.i am using
    marker1 = mGoogleMap.addMarker(new MarkerOptions()
    .position(latLng)
    .title(“San Francisco”)
    .snippet(“Population: 776733”));

    using this everytime a new marker is added rather updating the same marker to the new location.please help me achieve this

  60. juliya says:

    hi,, i tried ur code.but i was confused in output.
    the output shows nothing (blank screen).wat to do??
    plzz help me.

  61. […] add a marker to the current location, we need to know the LatLng. Refer the get current location in Android tutorial to find the current LatLng and using that we can add the marker easily as shown […]

  62. Manoj says:

    Nice Tutorial , it really helps me …thanks.

  63. ashish says:

    thanks Sir,

  64. Noha says:

    Can i try ready code from you?

    or if I can contact you to help me to discover the error in my code

  65. namrata says:

    hello sir,
    i m getting error nullpointer exception on location service plese can u help mi

  66. Anand Kumar says:

    Superb Tutorial Sir. Thanks a lot.

  67. Prakash says:

    We need physical android mobile to read the position or AVD is enough?

  68. sandeep singh says:

    i am new to android ,i tried the same but when i run it shows me only simple map.But i want to show also marker co-ordinate..

  69. Stephen Garside says:

    Hi, I am new to android development and was looking for a simple way to get the device location. The official google example is complete overkill, and your example if perfect – nice and easy to follow and understand without loads of code bloat! – Thanks for sharing

  70. Anonymous says:

    WOW!!! It really works! Thanks man!

    VEry good job!

  71. sandeep says:

    i need to develop android-app user activate gps and we get user address and we have store list and search nearest

    location of user and show result.can some one tell me for this app what step i have to do.

  72. fadha says:

    hi sir nice tutorial its working but sir i want to get current location name as well .how it could be possible

  73. fadha says:

    hi sir i need current location name to be shown if it gets current longitude and latitude. how it is possible???

  74. vshan says:

    hi i need to implement OnclickListener along with locationlistner.i am a newbie.i am getting the following error when i try to run:

    Error:(23, 8) java: com.example.sid.MainActivity is not abstract and does not override abstract method onProviderDisabled(java.lang.String) in android.location.LocationListener

    my syntax:public class MainActivity extends Activity implements OnClickListener,LocationListener

    can anyone please help??
    thanks in advance.

  75. kadev says:

    thank you sir it made my day

  76. Dhruvang Joshi says:

    Its working fine,but we need only city list within 100km from current location. So how to get that. Can u help me????

  77. sun says:

    the application is stopped its not even opening

  78. Anonymous says:

    nice tutorial sir
    it will help me lot

  79. Angad says:

    I could not get the 2 parameters (time and distance) used in requestLocationUpdates method. What I could understand is that after x time or x meters request for the user location but why both?
    And if we are giving both parameter then, which would be used(time interval or distance)?

    Also OnLocationChanged method would be called only when we requestLocation or will it be triggered every time user changes his location without even calling requestLocation method?

    Please clarify my doubts.

  80. Anonymous says:

    on launching application helloworld only displaying

  81. Anonymous says:

    onlocation changed method is nt calling when i run this application i kept debug statements to confirm that pls give solution

  82. Heir says:

    Helpful man and thx

  83. Elvis says:

    I am install the app on my phone, but only it only displaying –hello word– no latitude, no longetutide

  84. Shanmuga Sundaram says:

    Get Current Location in Android is not working…
    Please help me sir !

    The Above code which you uploaded at the beginning is not working now a days please reupload new code for getting current latitude & longtitude….

  85. Shanmuga Sundaram says:

    Sir, It works…

    By sitting in my room it don’t work …
    Just move around by installing the app it work and also takes some time to connect with the GPS …

    Thank you Once again…

  86. Jitu Varghese says:

    how can we detect a friend(other user) location from our app ?
    any suggestion…..

  87. Jitendra kushvaha says:

    Thanks you sir

  88. Navin says:

    i cant able to use this app in my phone. when i install and open it is showing a error message like: unexpected error occurred. what want to do for it. help me in this

  89. PARTH PATEL says:

    Hi,

    This tutorial is nice. App is working well in my mobile. But when I send coordinates from DDMS app is not reacting.

    -Parth

  90. kavinraj says:

    its working fine in emulator but it not working in my phone.only displaying hello world. how to solve this problem.

  91. […] mobile location. We have got GPS or network provider in the Android device and we can use that to get the current location in terms of latitude and longitude. Using the latitude and longitude we can get the address by […]

Comments are closed for "Get Current Location in Android".