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!

Answer from devunwired on Stack Overflow
🌐
GitHub
github.com › mkett › android-location-listener-example
GitHub - mkett/android-location-listener-example: Example to request location changes on Android · GitHub
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> Now we have to check if the permission is granted or otherwise let the user grant it. val dangPermToRequest: List<String> = checkMissingPermissions() if (dangPermToRequest.isNotEmpty()) { requestPermissions(dangPermToRequest) return } To use the location service, we need to get the location manager through getSystemService
Author   mkett
🌐
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 · 中文 – 简体
Discussions

android - How do I implement the LocationListener? - Stack Overflow
Here's my source code to get the longitude and the latitude, but how do I implement the statement inside the Location Listener, I am new in this, I really need help, please kindly offer your help, ... More on stackoverflow.com
🌐 stackoverflow.com
Error with inner class using android.location.LocationListener
LocationListener is an interface so you need to implement its methods. Looks like you have 3/6 methods. you're missing: onFlushComplete() onLocationChanged(list) onLocationChanged(location) See documentation here . I'm guessing your book is referencing an older version of LocationListener and the methods above are new additions. More on reddit.com
🌐 r/Kotlin
2
0
March 3, 2022
Difference between LocationListener and Fused Location API

Use the Fused Location API.

As the name suggests it's a 'fused' location provider, so it uses a mixture of GPS and network provided location to give you a trade-off between accuracy and battery consumption. It can also be updated independently of the OS, so it has a shorter release cycle for updates.

More on reddit.com
🌐 r/androiddev
9
5
January 29, 2015
13 Monitoring Apps To Monitor & Track Your Children’s Smartphone Activities
I have Tested Android007 and so far after 3 days iam liking the service . More on reddit.com
🌐 r/androidapps
27
12
January 29, 2019
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

🌐
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 - But as I said, this method fails most of the times. Hence, the best way I found to get user’s current latitude and longitude is Location Listener and get Location updates if the above method return null location. In your activity.java file you have to implement LocationListener method in seperate class and get updates as you click the button and then do the remaining taks.
🌐
Google
codelabs.developers.google.com › codelabs › while-in-use-location
Receive location updates in Android with Kotlin | Google Codelabs
March 27, 2026 - In your case, it is being used to get location information. In the base module, search for TODO: 2.2, Add foreground service type in the AndroidManifest.xml and add the following code to the <service> element: ... <application> ... <!-- Foreground services in Android 10+ require type. --> <!-- TODO: 2.2, Add foreground service type. --> <service android:name="com.example.android.whileinuselocation.ForegroundOnlyLocationService" android:enabled="true" android:exported="false" android:foregroundServiceType="location" /> </application>
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.

🌐
PCC
spot.pcc.edu › ~mgoodman › developer.android.com › guide › topics › location › strategies.html
Location Strategies | Android Developers
You might be creating an application that attempts to provide users with a set of options about where to go. For example, you're looking to provide a list of nearby restaurants, stores, and entertainment and the order of recommendations changes depending on the user location.
Find elsewhere
🌐
Google
developers.google.com › google play services › locationlistener
LocationListener | Google Play services | Google for Developers
October 31, 2024 - The onLocationChanged method is invoked when a new Location is available. ... A listener for receiving locations from the FusedLocationProviderClient.
🌐
Google
developers.google.com › google maps platform › android › maps sdk for android › show my location
Show My Location | Maps SDK for Android | Google for Developers
Display an error message // ... } } @Override protected void onResumeFragments() { super.onResumeFragments(); if (permissionDenied) { // Permission was not granted, display error dialog. showMissingPermissionError(); permissionDenied = false; } } /** * Displays a dialog with error message explaining that the location permission is missing. */ private void showMissingPermissionError() { PermissionUtils.PermissionDeniedDialog .newInstance(true).show(getSupportFragmentManager(), "dialog"); } } ... Git is required to run this sample locally. The following command clones the sample application repository. git clone git@github.com:googlemaps-samples/android-samples.git
🌐
Android Developers
minimum-viable-product.github.io › marshmallow-docs › training › location › receive-location-updates.html
Receiving Location Updates | Android Developers
In this lesson you require fine location detection, so that your app can get as precise a location as possible from the available location providers. Request this permission with the uses-permission element in your app manifest, as shown in the following example: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.gms.location.sample.locationupdates" > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> </manifest>
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › android.locations.ilocationlistener
ILocationListener Interface (Android.Locations) | Microsoft Learn
Used for receiving notifications when the device location has changed. [Android.Runtime.Register("android/location/LocationListener", "", "Android.Locations.ILocationListenerInvoker")] public interface ILocationListener : Android.Runtime.IJavaObject, IDisposable, Java.Interop.IJavaPeerable
🌐
Android Developers
developer.android.com › core areas › sensors and location › get the last known location
Get the last known location | Sensors and location | Android Developers
Once you have created the Location Services client you can get the last known location of a user's device. When your app is connected to these you can use the fused location provider's getLastLocation() method to retrieve the device location.
🌐
Developerlife
developerlife.com › 2010 › 10 › 20 › gps
Android Location Providers (gps, network, passive) | developerlife.com
October 20, 2010 - This is not a bad idea, since it ... of the listener going stale. You can switch providers at any time, and switch out a fine provider with a coarse one to save battery life, for example. There is really no limit to how often you can switch out providers. You can also do this when you discover that a provider is unavailable, via a call to the registered location ...
🌐
Reddit
reddit.com › r/kotlin › error with inner class using android.location.locationlistener
r/Kotlin on Reddit: Error with inner class using android.location.LocationListener
March 3, 2022 -

Hey guys,

in my studybooks I was adviced to put the following code in my learning project (toppings GPS):

"inner class NoteLocationListener : LocationListener {
override fun onLocationChanged(location: Location?) {
Log.d(javaClass.simpleName, "Empfangene Geodaten:\n$location")
val textview = findViewById<TextView>(R.id.textview_output)
textview.append("\nEmpfangene Geodaten:\n$location")
}

override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}

override fun onProviderEnabled(provider: String?) {
}

override fun onProviderDisabled(provider: String?) {
}
}
val locationListener = NoteLocationListener()"

This code was provided from my university. I checked it many times and got no typo. Unfortunately I get the following error, when I want to start this in my Android Studio project:

"Class 'NoteLocationListener' is not abstract and does not implement abstract member public abstract fun onLocationChanged(p0: Location): Unit defined in android.location.LocationListener"

Unfortunately I dont find the solution through this to continue with my learning book. Would somebody so kind and put me in the right direction? Since this code part was exactly in my book to use and work with + I am too unexperienced, I do not see, what is wrong here.

Thanks a lot!

🌐
Medium
rommansabbir.medium.com › location-listener-callback-in-android-643fa176cb2d
Location Listener Callback in Android | by Romman Sabbir | Medium
December 7, 2021 - Location Listener Callback in Android. A simple useful example of “How to get current Location from HelperClass/Callback” in Android using “FusedLocationProviderClient”.
🌐
GitHub
github.com › mkett › android-location-listener-example › blob › main › settings.gradle.kts
android-location-listener-example/settings.gradle.kts at main · mkett/android-location-listener-example
Example to request location changes on Android. Contribute to mkett/android-location-listener-example development by creating an account on GitHub.
Author   mkett
🌐
Dashwave
devblogs.dashwave.io › building-real-time-location-tracking-in-android
Building Real-Time Location Tracking in Android
July 23, 2023 - Example: Consider a food delivery app. By leveraging real-time location tracking, the app can provide live updates to customers about their order's whereabouts, enhancing transparency and trust.
🌐
DEV Community
dev.to › olubunmialegbeleye › location-services-the-android-14-maybe-15-too-way-4171
Location Services- the Android 14 (maybe 15 too) way - DEV Community
July 16, 2024 - By following the steps in this article, you can add location-based functionalities to enhance your Android apps, create more dynamic and contextually aware applications and deliver a superior user experience. For a complete example, you can refer to the repository at https://github.com/olubunmialegbeleye/Location.
🌐
Centron
centron.de › startseite › track your location with the android location api
Track Your Location with the Android Location API
February 7, 2025 - Our project consists of a MainActivity.java class responsible for user interaction and a LocationTrack.java class acting as a service to retrieve location updates. We’ve implemented runtime permissions crucial for Android 6.0+ devices, utilizing ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.