Android callback is a potential memory leak?

In my Android app, one of my actions involves creating instances of my other classes. Some classes should write on the screen. I want all layout interactions to be on the top level. So, I created an interface that includes a list of methods that can be called to display. Then I implement this interface in the main event. Finally, when instantiating classes, I pass the constructor "this" and it is saved and used for callbacks.

My question is: is there a danger of memory leaks due to the fact that I am passing an Activity object to one of its objects?

+4
source share
2 answers

I would consider the standard Android Handler mechanism for this (also supporting user callbacks for user interface changes).

Here is an example of a handler that defines a user callback to process the user interface:

http://developer.android.com/resources/samples/TicTacToeLib/src/com/example/android/tictactoe/library/GameActivity.html

While you guarantee that your "this" will be installed correctly, you should be safe enough, however, as soon as you start passing actions to other classes, it leaves the door open for potential memory leaks, as code fragments can now capture this instance and prevent it garbage collection in time when garbage collection should take place at the facility.

+2
source

If I understand your question correctly, you have separated some functions of the user interface interaction with the class and decorated it with it.

The simple answer to your question is no. Although you pass an instance of the "this" object to the object, the scope of the object itself is determined by Activity. In fact, the Android infrastructure covers a context that is not very similar to what you are doing. I believe that we can all agree that activity has a very limited lifespan.

The second point I wanted to make was the whole methodology. Android provides a mechanism to return to the main thread for interacting with the user interface. (post or asynctask, etc.). You must use one of these mechanisms to make some changes to the user interface (in the main thread). Therefore, my question is: could you write an anonymous inner class to perform this operation using asynctask, especially if this functionality is unique only to this operation.

+2
source

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


All Articles