Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android proper clean up/disposing

Is there a way to "clean up" objects and other variables you create? Or are they automatically disposed of or do I have this whole concept wrong? What is the proper way to go about doing this? I am trying to avoid the GC as much as possible.

like image 534
semajhan Avatar asked Jul 14 '11 19:07

semajhan


4 Answers

The only way to cleanup in an GC language with no memory management is the GC . You can force GC but its not recommended , the GC is pretty good , to be more proactive set objects to null for the GC to clean up.

Addition:

Also try to make objects as local as possible , that way they are GCed as they scope out.

like image 162
Ravi Vyas Avatar answered Sep 30 '22 19:09

Ravi Vyas


Calling System.gc() will force Garbage Collection to happen.

There is a system counting references to objects you create. If you are looping a lot and creating lots of objects you will create periods of time where they pile up. The system will collect the garbage when your processor is not doing anything, or it will wait till you need more free memory before collection occurs. If you have been processing for some time, you will experience hiccups in your performance due to Garbage Collection happening during your processes.

Please view this page and search for "Garbage Collection"

http://developer.android.com/guide/practices/design/performance.html

NOTE: Anything created with an Application Context will live until the end of the application execution. Anything created with an Activity Context will live until the end of the activity. This two situations can cause memory leaks!

like image 31
Chris Lucian Avatar answered Sep 30 '22 19:09

Chris Lucian


For a more complete answer specific to Android:

Make sure you review the application lifecycle for android. It will help you avoid activity leaks in Android.

like image 45
Codeman Avatar answered Sep 30 '22 18:09

Codeman


For the most part they are cleaned up as long as you do not maintain a reference to the object (variable). Something's like cursor's and bitmap's though need to be closed before they can be deleted to prevent memory leaks.

I don't think you have to worry about the GC as long as your object creation is not over the top. Note: GC is a part of java. You can't avoid it.

Addendum 1: If you really are that worried about it, you could reuse variables. That way you keep object creation to a minimum, but in so doing you will lose that variable and will be unable to store a wide range of data.

like image 28
ahodder Avatar answered Sep 30 '22 18:09

ahodder