Memory leakage in event listener

I have gone through the article In this article it is suggested to use a static inner class with a WeakReference . Many inner classes are used for event listeners. Can those inner class also cause memory leaks? Should those inner class be static?

  • Is it possible to start a Activity as a new process
  • Android Browser stretches image
  • Draw a dotted circle in Android View
  • Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
  • Android big picture style notification with multi line summary text
  • Android Studio: How to Migrate IntelliJ Project to Gradle?
  • Related posts:

    How do I make the colon vertical center in TextView
    EditText with SpannableStringBuilder and ImageSpan doesn't works fine
    Unable to pause activity, content view not yet created
    iOS AppDelegate equivalent in Android
    Android GPS incorrect location data on query
    HTTPS connection with basic auth result into Unauthorized
  • Android TextView Align text to Right and Left
  • android append '…' at the end textview
  • How to handle ListView click in Android
  • Android apk - How to exclude a .so file from a 3rd party dependency using gradle
  • passing intent extra to android broadcast receiver
  • Android - Loading, please wait
  • One Solution collect form web for “Memory leakage in event listener”

    Can those inner class also cause memory leakage?

    Possibly. It depends on what those listeners are registered upon.

    For example, a well-written OnClickListener for a Button should not result in a memory leak, because even though the OnClickListener may be an inner class and have an implicit reference to the Activity, the whole set of objects are all just tied to the activity. Hence, when the activity is destroyed, the activity, Button, and OnClickListener can all be garbage-collected as a whole.

    However, a LocationListener, registered with the LocationManager system service, is held by the process. Hence, even if the activity is destroyed, the listener will remain registered. If that listener is an inner class, it will continue to hold an implicit reference to the activity, and you will have a memory leak.

    Should those inner class be Staic one?

    Possibly. In most cases, the right answer is “if you are registering a listener other than with the UI, be sure to unregister it at an appropriate point”. In that case, there will be no leak.

    Can any one give me any example code how the event listener can use leak-proofly.

    Not in the abstract, no.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.