DEV Community

Cover image for Understanding Context in android Application
Ali sami hakemy
Ali sami hakemy

Posted on

Understanding Context in android Application

what is android context ?

  • used to get info about activity or application

  • both of Application Class and activity extends context class

  • used to access android resources and database etc ....

Context
almost used everywhere in application wrong use for context
can easily causes memory leaks

Main Types of Context

  1. Application Context
  2. Activity Context

Application Context

it is singleton instance can access in activity via (getApplicationContext) tie to application life cycle
used when you need to access context separate of activity lifecycle

Example Use: If you have to create a singleton object for your application and that object needs a context, always pass the application context.

Activity Context

available in activity and tie to activity lifecycle .The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.

Example Use: If you have to create an object whose lifecycle is attached to an activity, you can use the activity context.

ex: like get resources to display

How memory leaks is happens ?

memory leaks happens when you use activity context in task that is still running after activity destroy in this cases garbage collector can not remove reference of activity in memory

Simple Example

class LeaksClass(private val context: Context) {

    companion object {
        fun getInstance(context: Context): LeaksClass{
            return LeaksClass(context)
        }
    }

    fun doProcessing() {
        Thread {
            while (true) {
                Thread.sleep(100)
            }
        }.start()
    }

}
Enter fullscreen mode Exit fullscreen mode
    LeaksClass.getInstance(activityContext(this)).doProcessing()
Enter fullscreen mode Exit fullscreen mode

and class instance of this class and pass activity context and than start new activity or else... and make memory dumpheap
in this case garbage collector(GC) can not remove reference of
activity

Solution ->
` LeaksClass.getInstance(applicationContext).doProcessing()

Image description

debugging using android studio profiler or LeakCanary

https://square.github.io/leakcanary/getting_started/

Top comments (0)