Search code examples
androidlocationlistener

LocationListener how to stop when onLocationChanged() is called?


I want locationlistener to stop using gps when the location is changed, is this possible ?


Solution

  • public class MyActivity extends AppCompatActivity implements LocationListener {
    
        private LocationManager locationManager;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
    
        @Override
        public void onLocationChanged(Location location) {
            locationManager.removeUpdates(this);
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
    
        }
    
        @Override
        public void onProviderDisabled(String provider) {
    
        }
    
    }
    

    here this is the reference to LocationListener Interface.

    If you want only single location update then you can call

    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, Looper.getMainLooper());