Tuesday 31 March 2015

Avoid MEMORY LEAKS in Android

What is a memory leak?

Memory leaks means resources which are not available for GC (Garbage Collection).

There are two basic rules for writing efficient code:

  • Don't do work that you don't need to do.
  • Don't allocate memory if you can avoid it.
 Before starting, an Android developer should keep in mind that:

Android applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.

Know about Context:

On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context,
            1) Activity and
            2) Application.
It's usually the first one that the developer passes to classes and methods.

Now coming to the subject, GC will free resources which are not referenced. Sometimes a single reference can prevent a large set of objects from being garbage collected. eg: Some static variables which are referenced in an activity may not be for GC, because as long as the reference exists, the Activity will be kept in memory, leaking all of its views.

Lets have a look at a Code snippet :

Here, the static drawable sBackground will leak.

Solution:

The solution here is when the activity gets destroyed, release the drawable in destroy and unbind all callbacks 
Here, our onDestroy() will look like this, 

        
So that the drawable sBackground will be available for GC and can prevent memory leak when activity gets destroyed.
Another common cause for memory leak is non-static inner classes in an Activity. This commonly comes when creating fragments in an Activity. Either create static inner classes or create stand alone classes.

Reference:
  http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html
  http://smartandroidians.blogspot.in/ 

2 comments:

  1. Thanks for sharing great post. I really like this post. ....!!!

    If you want to make custom website & application you can contact us on our Mobile App Development Company and Android App Development Company and grow your business also than touch with SEO Services Company anytime.

    ReplyDelete