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.
🌐
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
🌐
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
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 10811400 › android-location-listener-or-android-events-in-general
Android Location Listener (or Android Events in general) - Stack Overflow
// Acquire a reference to the system ... LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. makeUseOfN...
🌐
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.
🌐
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)
🌐
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
🌐
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) { } }
🌐
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
🌐
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 // ...
🌐
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 · 中文 – 简体
🌐
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.
🌐
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.