Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * SomeActivity is some heavyweight object that is very costly if leaked.
- */
- public class SomeActivity extends Activity implements SomeListenerInterface {
- /*
- * MyListener is a minimal implementation of the necessary interfaces that forwards all of its
- * method calls to the outer class if the parent has not been GC'd.
- *
- * Crucially, because this listener only holds a weak reference, it won't prevent SomeActivity from being GC'd. And because MyListener is a small object, it may still be leaked but it's a matter of bytes being leaked rather than megabytes if an Activity were leaked.
- *
- * This class must be static. A non-static inner class will hold a strong reference to the outer class which we can't have.
- */
- static class MyListener implements SomeListenerInterface {
- private WeakReference<SomeActivity> ref;
- public MyListener(WeakReference<SomeActivity> ref) {
- this.ref = ref;
- }
- @Override
- public void someMethod(String arg) {
- // grab a temporary strong reference and check to make sure SomeActivity hasn't been GC'd.
- SomeActivity a = ref.get();
- if (a != null) {
- a.someMethod(arg);
- }
- }
- }
- @Override
- public void onCreate(Bundle savedState) {
- // instead of directly registering SomeActivity, register the custom listener.
- WhateverManager.addListener(new MyListener(new WeakReference(this)));
- ...
- }
- @Override
- public void someMethod(String arg) {
- // do whatever here
- System.out.println(arg);
- }
- }
Add Comment
Please, Sign In to add comment