Definition of Context :
- Context represents environment data.
- It provides access to things such as databases.
Different methods by which you can get context:
- or this (when in the activity class)
Okay, now lets see the difference between getContext(), this, getBaseContext(), and getApplicationContext().
Different types of Context:
In truth, only the ContextThemeWrapper is UI Context which aids Context + Your theme. Activity extends ContextThemeWrapper. This is the reason that, when you inflate any XML, those views are themed. If you inflate your layout with Non-UI context, your layout will not be themed. Go further, try it.
When you use Activity as a placeholder for Context, you are assured to be using UI Context. If you use the getContext method from the Fragment, you are indirectly using Activity (if you attached Fragment via fragment manager in the activity).
But view.getContext() is not guaranteed to be UI Context.
If View was instantiated using Layout Inflater and passed UI Context, you get UI Context back. But if it was instantiated by not passing UI Context, you get the other context back.
- Activity – Instance of your activity (this)
- Fragment – getContext() in Fragment
- View – getContext() in View (if View was constructed using UI-Context)
Anything except the UI Context is a Non-UI Context. Technically, anything which is not ContextThemeWrapper is Non-UI Context.
Non-UI Context is allowed to do more or less everything UI-Context can do (bad design spotted). But as we pointed out above, you will lose theming.
- Application instance as the context.
- Activity – getApplicationContext() in Activity.
- Broadcast Receiver – Context received in the broadcast receiver.
- Service – Instance of your service (this) & getApplicationContext() in Service
- Context – getApplicationContext() in Context instance.
Lastly, We have reduced it a little bit by putting Context in two buckets. UI Context is Context (+) Theming, and technically any class which is a subclass of a ContextThemeWrapper comes in this bucket.
Memory Leak or Crash:
Yes, it’s a worst case scenario when you use context in the wrong place. If you are new to the Android app development world, let me share some knowledge. Memory leaks are inversely proportional to your experience. Every Android developer has leaked memory. There is no shame in doing so.
Shame is when you repeat the mistake again and leak it the same way. If you leak memory a different way every time, best wishes you are growing. Better yet, get the application context to avoid memory leaks.
- Do you need to access UI related stuff? Use UI-Context. Inflating Views and showing dialogue are the two use cases I can think of.
- Otherwise, use Non-UI Context.
- Make sure you do not pass short-living context to long-living objects.
P.S: Image courtesy – nimbledroid.com