Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android callback - is this a potential memory leak?

In my Android application, one of my activities includes instantiation of other classes of mine. Some of the classes need to write to the screen. I want to keep all the layout interaction at the top level. So, I created an Interface which includes a list of methods that can be called to output to the screen. I then Implement this interface in the main Activity. Finally, when instantiating the classes I pass "this" to the constructor and it is saved and used for the callbacks.

My question is: is there a danger of memory leaks due to me passing the Activity object itself into one of its objects?

like image 507
theblitz Avatar asked Oct 12 '22 08:10

theblitz


2 Answers

I would look into the standard Android Handler mechanism for this (also supporting custom callbacks for UI changes).

Here's an example of a handler defining a custom callback to handle UI changes :

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

As long as you can ensure that your "this" is scoped properly, you should be pretty safe, however, as soon as you start passing activities around to other classes, it does leave the door open to potential memory leaks, as pieces of code can get a hold of that instance now and prevent it from being garbage collected in time where garbage collection should have occured on the object.

like image 150
ddewaele Avatar answered Oct 20 '22 10:10

ddewaele


If I understand your question correctly, you have abstracted some UI interaction functionality in to a class and decorated your activity with it.

The simple answer to your question is no. Although you pass an instance of "this" to the object, the scope of the object itself is governed by Activity. In fact android framework passes around context, not very similar to what you do. I believe we can all agree that Activity has a very limited lifetime.

The second point I wanted to make is, about the whole methodology itself. Android provides mechanism to post back to the main thread to perform UI interactions. (post or asynctask etc..) You should use one of these mechanism to make some changes to UI (in the main thread). So my question is, could you not write an anonymous inner class to perform this operation using asynctask, especially if this functionality is unique only to this Activity.

like image 23
uncaught_exceptions Avatar answered Oct 20 '22 09:10

uncaught_exceptions