I have an Activity that implements LocationListener.
public class MyActivity extends MapActivity implements LocationListener
In my activity, I register a locationlistener in the onCreate()
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
In the onDestroy method, I'm removing the registration for my locationlistener.
@Override
protected void onDestroy() {
Utils.addDebugMsg(this,"onDestroy");
lm.removeUpdates(this);
super.onDestroy();
}
In my application, I can change the minTime and distance, so I re-initialize my listener like this :
private void initializeGpsListener() {
lm.removeUpdates(this);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, distance, this);
}
For debugging purposes, I write something to the screen whenever a provider is enabled (in this case GPS).
@Override
public void onProviderEnabled(String provider) {
Utils.addDebugMsg(this,"onProviderEnabled : " + provider);
}
What I noticed is that sometimes, multiple instances of my activity (or locationlistener) are "kept around". Each time I turn the GPS provider on, instead of seeing 1 statement "onProviderEnabled : GPS", I see several different instances of my Activity printing this line (all at the same time).
How do I clean up these listeners ( = my activities), and make sure that only 1 remains active throughout the application.
The Activity implemented OnSharedPreferenceChangeListener.
During onCreate, the activity was registered as a PreferenceChangelistener, but not unregistered in the onDestroy().
As such, even after the activity was destroyed, there was still a reference to the activity, causing the duplicate messages.