What is Context in Android and What is the proper way to use it?

By | December 7, 2018

Lets see what a Context is…

  • Context : Current State of the application.
  • Context : Handle of the application.
  • Context : Provides access to the resources, preferences, accessing database etc.

Activity inherits from the Context.

Context is the most important part of the Android application and its everywhere.

If you wrongly use Context, it can lead to memory leaks.

Different types of Context

  • Application Context – getApplicationContext()
  • Activity Context – Context of the Activity.
  • getContext()

Application Context

  • It is Singleton.
  • Accessed via getApplicationContext()
  • Can be used anywhere where you need context separate from the current context.

Example : File access or if you have a singleton class of you own, always pass the getApplicationContext() to get resources inside that class.

What you are doing wrong?

If you pass Activity context, then it will keep reference to the Activity and will lead to memory leaks since the Activity will not be garbage colleted.

When to use getApplicationContext()?

Use getApplicationContext() when you need a context that needs to live longer than the current context(eg: Activity context).

Activity Context

When to use ?

When you want to access resources specific to a current Activity.

Example : If you are creating an object inside an Activity, use Activity Context.

TextView tv = new TextView(this); // Here 'this' is the Activity Context

getContext() in ContentProvider

This context is the application context and can be used similar to the application context. This can be accessed via getContext() method.

What are developer should remember?

  • Use getApplicationContext() only when you are accessing resources that are not tied to an Activity.
  • Use Activity Context only when the resources you access wont extend beyond the Activity lifecycle.

These are one of the basics of Android Development. Learn good and write good code.

Leave a Reply

Your email address will not be published. Required fields are marked *