What is Context?

Context is an abstract class, whose implementation is provided by Android System.

It provide acces to application related resources,databses,shared preferences...

We have different ways to access the context.

  • getContext()
  • getBaseContext()
  • getApplicationContext()
  • getActionBar().getThemedContext()

 

When to use getContext()?

Any instance which is not running long time, there we can use getContext().

We can use it in long running instances but we need to hanlde it by theire lifecycle methods to avoid memory leaks.

 

When to use getBaseContext()?

Inside activity life cycle we can use the getBaseContext(), this will be lives until the activity lifecycle alive.

 

When to use getApplicationContext()?

getApplicationContext() returns the application context of entire application. It will live untile the application life cycle, once application terminated it will destory

 

When to use getThemedContext()?

This context will be used to hanlde the views theme context inside the actionbar.

 

Note: we have to use proper context on the lifecycle of each instance to avoid the memory leaks in the application.