Guest User

Untitled

a guest
Jun 24th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /*
  2. * SomeActivity is some heavyweight object that is very costly if leaked.
  3. */
  4. public class SomeActivity extends Activity implements SomeListenerInterface {
  5.  
  6. /*
  7. * MyListener is a minimal implementation of the necessary interfaces that forwards all of its
  8. * method calls to the outer class if the parent has not been GC'd.
  9. *
  10. * 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.
  11. *
  12. * This class must be static. A non-static inner class will hold a strong reference to the outer class which we can't have.
  13. */
  14. static class MyListener implements SomeListenerInterface {
  15. private WeakReference<SomeActivity> ref;
  16. public MyListener(WeakReference<SomeActivity> ref) {
  17. this.ref = ref;
  18. }
  19.  
  20. @Override
  21. public void someMethod(String arg) {
  22. // grab a temporary strong reference and check to make sure SomeActivity hasn't been GC'd.
  23. SomeActivity a = ref.get();
  24. if (a != null) {
  25. a.someMethod(arg);
  26. }
  27. }
  28. }
  29.  
  30. @Override
  31. public void onCreate(Bundle savedState) {
  32. // instead of directly registering SomeActivity, register the custom listener.
  33. WhateverManager.addListener(new MyListener(new WeakReference(this)));
  34. ...
  35. }
  36.  
  37. @Override
  38. public void someMethod(String arg) {
  39. // do whatever here
  40. System.out.println(arg);
  41. }
  42.  
  43. }
Add Comment
Please, Sign In to add comment