Search code examples
androidlocationlistenerlifecycleonpause

Stop a location listener activity when the user presses the back button, or when a new intent is made


This app will beep whenever the user's location changes. The problem is, the app will continue monitoring the user's location even after they have left the app and it is in the background.

How do I stop the location listener, once the app goes into the background?

I think I have to add something to the OnPause(), but I can't make it work.

package com.example.locationbeeper;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;



public class MainActivity extends FragmentActivity implements LocationListener {

    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // set up location manager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 200, 5, this);  // time in miliseconds, distance in meters (Distance drains battry life) originally set to 20000 and 0
    }

    @Override
    public void onLocationChanged(Location location) {
        // beep when location changed
        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        tg.startTone(ToneGenerator.TONE_PROP_BEEP);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPause(){
        super.onPause();
        
        locationManager = null;
    }


}


Solution

  • Based on your requirement, you can add below lines either in onPause() or onStop() callback method of your activity.

    if(locationManager !=null)
          locationManager.removeUpdates(this);