Can a remote ViewTreeObserver listener cause a memory leak?

I listen to view layout changes using OnGlobalLayoutListener :

 view.getViewTreeObserver().addOnGlobalLayoutListener(myListener); 

Since I am interested in the events of this listener, as long as the view exists, I do not see the need to call removeOnGlobalLayoutListener(myListener) .

Could this cause a memory leak or garbage collector assembled with the view? Suppose a listener has a link to a view.


Backgound is that I want to create a module that can be attached to specific views and do things based on layout changes. If removal is not required, creating it will be as simple as new FancyModule(theView) , and then the constructor will take care of binding the listener. If deletion is necessary, I will have to implement a destructor method that I would like to prevent.

+5
source share
2 answers

The potential memory leak depends only on your architecture.

This is usually normal so as not to call removeOnGlobalLayoutListener(myListener) . View contains a link to ViewTreeObserver , which contains a link to the added OnGlobalLayoutListener . Unless you have another reference to the listener, this is garbage collected on presentation.

Now, if your OnGlobalLayoutListener implementation contains a reference to the view, it is still beautiful. The reverse loop is not a problem for the Android garbage collector.

The problem can be created if you have another component that contains a reference to the OnGlobalLayoutListener implementation. If the component lives longer than the view (for example, it is held through the application object), you create a memory leak from the view (and context) through the listener.

It’s important not to hold the view when it is no longer in use. An easy way to avoid eye leak is to use WeakReference .

+3
source

Yes, it can leak. Here's a sample footprint from LeakCanary,

  • com.xxx. There was a leak:
  • GC ROOT static android.view.inputmethod.InputMethodManager.sInstance
  • links android.view.inputmethod.InputMethodManager.mCurRootView
  • links com.android.internal.policy.DecorView.mAttachInfo
  • links android.view.View $ AttachInfo.mTreeObserver
  • links android.view.ViewTreeObserver.mOnGlobalLayoutListeners
  • links android.view.ViewTreeObserver $ CopyOnWriteArray.mData li>
  • links java.util.ArrayList.elementData li>
  • refers to the java.lang.Object [] array. [0]
  • links com.xxx.Activity $ setExpandedToolbarHeight $ layoutListener $ 1.this $ 0 (anonymous implementation of android.view.ViewTreeObserver $ OnGlobalLayoutListener)
  • leak com.xxx. Acctivity instance
0
source

Source: https://habr.com/ru/post/1247689/


All Articles