What is the difference between getContext()
, getApplicationContext()
, getBaseContext()
, and "this
"?
Though this is simple question I am unable to understand the basic difference between them. Please give some easy examples if possible.
getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity.
getContext() - Returns the context view only current running activity. getActivity()- Return the Activity this fragment is currently associated with. getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .
This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component. Actually in general it is better to use getApplicationContext() since it will less likey lead to memory leaks.
In android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.
View.getContext()
: Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext()
: Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
ContextWrapper.getBaseContext()
: If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With