3

I have a preferenceActivity that implements OnSharedPreferenceChangeListener and I have implemented the onSharedPreferenceChanged method. I register and unregister a listener in onResume and onPause() using the keyword "this"

All works well so far but I am concerned that my listener will be garbage collected, as described in this post. Is what I am doing bad practice? Seems too easy but if it not broken I don't want to fix it!

My activity

public class MyPreferences extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {
    //blah blah blah
}

My onSharedPreferenceChangeListener

@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    doMyStuff();
} //onSharedPreferenceChanged

onResume() & onPause()

@Override     
protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);     
} //end onResume

@Override     
protected void onPause() {         
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
} //end onPause
Community
  • 1
  • 1
Mel
  • 6,214
  • 10
  • 54
  • 71

2 Answers2

0

I don't think this will be an issue, since the class itself is the listener, and will only be destroyed and garbage collected after finish() has been called.

Glitch
  • 2,785
  • 1
  • 27
  • 50
0

this link you posted is creating an instance each time the activity resumes

so how about keep the reference

OnSharedPreferenceChangeListener myPrefListner = new OnSharedPreferenceChangeListener(){
      public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
         // your stuff
      }
}

and in your onResume and onPause

@Override     
protected void onResume() {
    super.onResume();          
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);     
}



@Override     
protected void onPause() {         
    super.onPause();          
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);

}

this will very similar to what you are doing except we are maintaining a hard reference.

Samuel
  • 9,883
  • 5
  • 45
  • 57
  • it seems that any preference change notification between onPause() and onResume() will NOT be received by the object at all, because the preference activity will run in this timeframe. This will cause your app to miss the change notifications. – Califf Nov 25 '15 at 18:28
  • Wow 4 years..., OP has implemented the listener in the preference activity. If I am forced to change the same preference from the outside I would handle it there aswell. – Samuel Nov 26 '15 at 05:10