shalskar / PeekAndPop

497 stars 65 forks source link

Memory and thread allocation without freeing: a possible solution #28

Open adlerosn opened 5 years ago

adlerosn commented 5 years ago

The attribute PeekAndPop.longHoldTimer holds a thread that requires manual destruction. The attribute PeekAndPop.gestureDetector also creates a handler that holds a thread and also requires manual destruction. Keeping a thread alive means that the garbage collector cannot free such object. Also, keep in mind that the kernel limits how many threads a process can have. It's common to the average app programmer (who is your library user) to create one PeekAndPop instance inside a RecyclerView.Adapter child on every onBindViewHolder call and just believe that when the view gets another PeekAndPop instance, the previous one will be released and then freed automatically.

After getting several LIBC errors with code 6 and fewer OutOfMemoryExceptions with weird visual glitches and figuring out the source of the problem, I wrote a partial reimplementation (drop-in replacement) that worked well enough for what I wanted to do (API 21+). The architecture of how it works is slightly different, as it inflates your peekLayout orphan, uses the View's existing setOnLongClickListener method to display an AlertDialog created by AlertDialog.Builder with a transparent background and with that previously orphan view as its own child and makes that view orphan again once the AlertDialog gets dismissed. This ensures that everything can be freed once every reference to a given PeekAndPop object gets lost. The major drawback is that I couldn't find a precise way to know what the user is touching. Feel free to take and use that piece of code under the MIT license, but you'll need to rewrite some few extension functions I used and didn't send in that package.

Starting from that architecture, implementing the requests #6 and #22 would be a simpler task, issue #27 wouldn't happen without any consistency and issues #13 and #21 wouldn't happen as result of the behaviour of code you wrote.