Android WeakReference
WeakReference
Reference : Basically, in Java, GC release memory if the object is not refereed from other places.
In Android, there are Strong reference(general), WeakReference
SoftReference, WeakReference
What situation do we use?
One of example to use WeakReference is view reference.
Different from iOS, Android doesn’t have Notification.
Example) Use singleton manager and, it has Set reference.
public class ImageButtonManager { private static ImageButtonManager instance; private Set<WeakReference<ImageButton>> buttons = new HashSet(); public static synchronized ImageButtonManager getInstance() { if (instance == null) { instance = new ImageButtonManager (); } } private ImageButtonManager() { } public void register(ImageButton button) { if (!this.buttons.contains(button) { this.buttons.add(button); } } private synchronized void notify() { for (Iterator localIterator = this.buttons.iterator(); localIterator.hasNext();) { WeakReference localWeakReference = (WeakReference)localIterator.next(); if (localWeakReference.get() == null) { localIterator.remove(); } else { ImageButton localButton = (ImageButton)localWeakReference.get(); // Do something to localButton } } } }