Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getApplicationContext() and getActivity()

Tags:

android

What is the difference between getApplicationContext() and getActivity() and this in Android?

like image 929
AppB Avatar asked Jun 06 '16 10:06

AppB


People also ask

What is the difference between getContext () getApplicationContext () getBaseContext ()?

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.

What is the difference between getActivity and getContext?

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 .

What is difference between context and activity?

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.

What is the difference between this context and getApplicationContext which one to use when?

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.


2 Answers

There is a lot of difference between :

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().

Also check :

https://stackoverflow.com/a/10641257/4018207 https://developer.android.com/reference/android/view/View.html#getContext%28%29

like image 151
AndiGeeky Avatar answered Oct 03 '22 06:10

AndiGeeky


There is huge difference. An android application can have more than one activity, when you say getApplicationContext(), it gives you the context of entire application: see details :

However when you say getActivity() it just gives you the instance of activity which you are currently in.

like image 27
Ashish Rawat Avatar answered Oct 03 '22 06:10

Ashish Rawat