Just use this code :

public class Location extends AppCompatActivity {
    LocationManager locationManager;
    Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        mContext=this;
        locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
                2000,
                10, locationListenerGPS);
        isLocationEnabled();

    }

    LocationListener locationListenerGPS=new LocationListener() {
        @Override
        public void onLocationChanged(android.location.Location location) {
            double latitude=location.getLatitude();
            double longitude=location.getLongitude();
            String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
            Toast.makeText(mContext,msg,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


    protected void onResume(){
        super.onResume();
        isLocationEnabled();
    }

    private void isLocationEnabled() {

        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
            alertDialog.setTitle("Enable Location");
            alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
            alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.cancel();
                }
            });
            AlertDialog alert=alertDialog.create();
            alert.show();
        }
        else{
            AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
            alertDialog.setTitle("Confirm Location");
            alertDialog.setMessage("Your Location is enabled, please enjoy");
            alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.cancel();
                }
            });
            AlertDialog alert=alertDialog.create();
            alert.show();
        }
    }
}

The parameters of requestLocationUpdates methods are as follows:

provider:The name of the provider with which we would like to register.
minTime:Minimum time interval between location updates (in milliseconds).
minDistance:Minimum distance between location updates (in meters).
listener:A LocationListener whose onLocationChanged(Location) method will be called for each location update.

Permissions:

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

Add above permissions to manifest file for the version lower than lollipop and for marshmallow and higher version use runtime permission.

Answer from user3164401 on Stack Overflow
🌐
Android Developers
developer.android.com › api reference › locationlistener
LocationListener | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
Top answer
1 of 1
16

Just use this code :

public class Location extends AppCompatActivity {
    LocationManager locationManager;
    Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        mContext=this;
        locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
                2000,
                10, locationListenerGPS);
        isLocationEnabled();

    }

    LocationListener locationListenerGPS=new LocationListener() {
        @Override
        public void onLocationChanged(android.location.Location location) {
            double latitude=location.getLatitude();
            double longitude=location.getLongitude();
            String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
            Toast.makeText(mContext,msg,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


    protected void onResume(){
        super.onResume();
        isLocationEnabled();
    }

    private void isLocationEnabled() {

        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
            alertDialog.setTitle("Enable Location");
            alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
            alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            });
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.cancel();
                }
            });
            AlertDialog alert=alertDialog.create();
            alert.show();
        }
        else{
            AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
            alertDialog.setTitle("Confirm Location");
            alertDialog.setMessage("Your Location is enabled, please enjoy");
            alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.cancel();
                }
            });
            AlertDialog alert=alertDialog.create();
            alert.show();
        }
    }
}

The parameters of requestLocationUpdates methods are as follows:

provider:The name of the provider with which we would like to register.
minTime:Minimum time interval between location updates (in milliseconds).
minDistance:Minimum distance between location updates (in meters).
listener:A LocationListener whose onLocationChanged(Location) method will be called for each location update.

Permissions:

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

Add above permissions to manifest file for the version lower than lollipop and for marshmallow and higher version use runtime permission.

🌐
Google
developers.google.com › google play services › locationlistener
LocationListener | Google Play services | Google for Developers
October 31, 2024 - LocationListener is an interface for receiving locations from the FusedLocationProviderClient.
🌐
Java Tips
javatips.net › api › android.location.locationlistener
Java Examples for android.location.LocationListener
public static void getRecentLocation(final LocationListener listener) { Location last = LocationUtils.getLastLocation(); if (last == null || LocationUtils.getAgeInSeconds(last.getTime()) > 60) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_MEDIUM); final LocationManager locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE); List<String> providers = locationManager.getProviders(criteria, /* enabledOnly */ true); if (providers.size() == 0) { listener.onLocationFailed(); return; } locationSuccess = false; final android.location.Loca
🌐
GitHub
github.com › mkett › android-location-listener-example
GitHub - mkett/android-location-listener-example: Example to request location changes on Android · GitHub
private val locationListener = object : LocationListener { override fun onLocationChanged(location: Location) { ... } } private fun registerToLocationListener() { ...
Author   mkett
🌐
DigitalOcean
digitalocean.com › community › tutorials › android-location-api-tracking-gps
Android Location API to track your current location | DigitalOcean
August 3, 2022 - public class LocationTrack extends Service implements LocationListener { private final Context mContext; boolean checkGPS = false; boolean checkNetwork = false; boolean canGetLocation = false; Location loc; double latitude; double longitude; private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; protected LocationManager locationManager; public LocationTrack(Context mContext) { this.mContext = mContext; getLocation(); } private Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LO
🌐
Java2s
java2s.com › example › java-api › android › location › locationlistener › locationlistener-0-0.html
Example usage for android.location LocationListener LocationListener
public LocationSynchronizer(FragmentActivity context) { manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); listener = new LocationListener() { @Override/* www .j a va 2s.c o m*/ public void onLocationChanged(Location l) { location = l; updateViews(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { if ((provider.equals(LocationManager.GPS_PROVIDER) && !manager.isProviderEnabled(LocationManager.NETWORK_PROVID
🌐
Vogella
vogella.com › tutorials › AndroidLocationAPI › article.html
Android Location API with the fused location provider - Tutorial
February 26, 2026 - package de.vogella.android.locationsapi.simple; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class ShowLocationActivity extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; private LocationManager locationManager; private String provider; /** Called when the activity is first created.
Find elsewhere
🌐
Google
developers.google.com › google maps platform › android › navigation sdk for android › roadsnappedlocationprovider.locationlistener
RoadSnappedLocationProvider.LocationListener | Navigation SDK for Android | Google for Developers
When available, maps to a boolean value that indicates whether the location was snapped to the best available road. Note that this value may sometimes have hiccups and may differ from what aGMM UI shows. Retrieve the value with location.getExtras().getBoolean(LocationListener.IS_ROAD_SNAPPED_KEY)
🌐
Medium
medium.com › @grudransh1 › best-way-to-get-users-location-in-android-app-using-location-listener-from-java-in-android-studio-77882f8b87fd
Best way to get user’s location in android app using Location Listener from JAVA in android studio | by Rudransh Gupta | Medium
May 17, 2020 - Now coming to the implementation of complete process, first calling getLastKnownLocation will return null, thus we will make an instance of LocationListener class and ask for user to open the GPS in mobile.
Top answer
1 of 4
42

The way that I would typically implement this requirement is using a bound Service implementation, like the one in the Local Service Sample in the SDK Documentation. Obviously you're familiar with the advantage of the Service allowing you to create all the location code only once.

Accessing the Service through Bindings allows the Service to start and stop itself so it isn't running when your application isn't in the foreground (it will die as soon as no more Activities are bound). The key, IMO, to making this work well is to BIND the service in onStart() and UNBIND in onStop(), because those two calls overlap as you move from one Activity to another (Second Activity Starts before the First one Stops). This keeps the Service from dying when moving around inside the app, and only lets the service die when the entire application (or at least any part interested in location) leaves the foreground.

With Bindings, you don't have to pass the Location data in a Broadcast, because the Activity can call methods directly on the Service to get the latest location. However, a Broadcast would still be advantageous as a method of indicating WHEN a new update is available...but this would just become a notifier to the listening Activity to call the getLocation() method on the Service.

My $0.02. Hope that Helps!

2 of 4
18

I got the same problem and I tried to solve it with the good answer of Devunwired, but I had some troubles. I couldn't find a way to stop the service and when I finished my app the GPS-module was still running. So i found another way:

I wrote a GPS.java class:

public class GPS {

    private IGPSActivity main;

    // Helper for GPS-Position
    private LocationListener mlocListener;
    private LocationManager mlocManager;

    private boolean isRunning;

    public GPS(IGPSActivity main) {
        this.main = main;

        // GPS Position
        mlocManager = (LocationManager) ((Activity) this.main).getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        // GPS Position END
        this.isRunning = true;
    }

    public void stopGPS() {
        if(isRunning) {
            mlocManager.removeUpdates(mlocListener);
            this.isRunning = false;
        }
    }

    public void resumeGPS() {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        this.isRunning = true;
    }

    public boolean isRunning() {
        return this.isRunning;
    }

    public class MyLocationListener implements LocationListener {

        private final String TAG = MyLocationListener.class.getSimpleName();

        @Override
        public void onLocationChanged(Location loc) {
            GPS.this.main.locationChanged(loc.getLongitude(), loc.getLatitude());
        }

        @Override
        public void onProviderDisabled(String provider) {
            GPS.this.main.displayGPSSettingsDialog();
        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

    }

}

This class is used in every Activity which needs the GPS coordinates. Every Activity has to implement the following Interface (needed for the communication):

public interface IGPSActivity {
    public void locationChanged(double longitude, double latitude);
    public void displayGPSSettingsDialog();
}

Now my main Activity looks like that:

public class MainActivity extends Activity implements IGPSActivity {

    private GPS gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        gps = new GPS(this);
    }


    @Override
    protected void onResume() { 
        if(!gps.isRunning()) gps.resumeGPS();   
        super.onResume();
    }

    @Override
    protected void onStop() {
        gps.stopGPS();
        super.onStop();
    }


    public void locationChanged(double longitude, double latitude) {
        Log.d(TAG, "Main-Longitude: " + longitude);
        Log.d(TAG, "Main-Latitude: " + latitude);
    }


    @Override
    public void displayGPSSettingsDialog() {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
    }
}

and a second one like that:

public class TEST4GPS extends Activity implements IGPSActivity{

    private GPS gps;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.gps = new GPS(this);
    }

    @Override
    public void locationChanged(double longitude, double latitude) {
        Log.d("TEST", "Test-Longitude: " + longitude);
        Log.d("TEST", "Test-Latitude: " + latitude);

    }

    @Override
    protected void onResume() { 
        if(!gps.isRunning()) gps.resumeGPS();   
        super. onResume();
    }

    @Override
    protected void onStop() {
        gps.stopGPS();
        super.onStop();
    }

    @Override
    public void displayGPSSettingsDialog() {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);

    }
}

It's not as beautiful as the solution of Devunwired, but it works for me. cya

🌐
Vanderbilt
dre.vanderbilt.edu › ~schmidt › android › android-4.0 › out › target › common › docs › doc-comment-check › reference › android › location › LocationManager.html
LocationManager | Android Developers
Registers the current activity to be notified periodically based on the specified criteria. Periodically, the supplied LocationListener will be called with the current Location or with status updates.
🌐
Android Developers
developer.android.com › api reference › locationmanager
LocationManager | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Android Developers
stuff.mit.edu › afs › sipb › project › android › docs › training › basics › location › currentlocation.html
Obtaining the Current Location | Android Developers
private final LocationListener listener = new LocationListener() { @Override public void onLocationChanged(Location location) { // A new location update is received. Do something useful with it. In this case, // we're sending the update to a handler which then updates the UI with the new // ...
🌐
Technobyte
technobyte.org › locationmanager-tutorial-android-studio
LocationManager Tutorial in Android
April 21, 2024 - LocationListener listener: the listener to receive location updates This value cannot be null. ... We will now begin creating our app. The function of the app is pretty simple and straightforward: get the location coordinates of the user and display it on the button click. Create a new project with an empty activity. ... <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_p
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
GitHub
github.com › rommansabbir › LocationListener-Android
GitHub - rommansabbir/LocationListener-Android: A simple library for Android to get current geo location
class MainActivity : AppCompatActivity(), PermissionCallback { override fun onPermissionRequest(isGranted: Boolean) { /** * Check if granted or not */ if(isGranted){ /** * Get location after a period of time */ LocationListener.getLocationPeriodic(5000, object : LocationCallback { override fun onLocationSuccess(location: Location) { Toast.makeText(this@MainActivity, "${location.latitude}, ${location.longitude}", Toast.LENGTH_SHORT).show() } }) /** * Get location for a single time */ LocationListener.getLocation(object : LocationCallback{ override fun onLocationSuccess(location: Location) { Toast.makeText(this@MainActivity, "${location.latitude}, ${location.longitude}", Toast.LENGTH_SHORT).show() } }) } } override fun onCreate(savedInstanceState: Bundle?)
Author   rommansabbir
🌐
Processing
android.processing.org › tutorials › location
Processing for Android
class MyLocationListener implements LocationListener { public void onLocationChanged(Location location) { currentLatitude = (float)location.getLatitude(); currentLongitude = (float)location.getLongitude(); currentAccuracy = (float)location.getAccuracy(); currentProvider = location.getProvider(); } public void onProviderDisabled (String provider) { currentProvider = ""; } public void onProviderEnabled (String provider) { currentProvider = provider; } public void onStatusChanged (String provider, int status, Bundle extras) { } }
🌐
Codexpedia
codexpedia.com › home › android › android locationmanager code example
Android LocationManager Code Example - Codexpedia
December 7, 2015 - Lastly, add the MyLocationListener in the Activity class. [code language=”java”] private class MyLocationListener implements LocationListener {
🌐
Java Code Geeks
examples.javacodegeeks.com › home › android › core › location
Android Location Based Services Example - Java Code Geeks
December 23, 2013 - The result is shown in the image below. We can notice that the longitude and the latitude change, while the onLocationChanged method on LocationListener is called. This was an example of Location Based Services in Android.