F
F
foonfyrick2020-12-14 08:21:34
Android
foonfyrick, 2020-12-14 08:21:34

Can you please explain getApplicationContext(), getContext(), getBaseContext()?

I read that: getApplicationContext() - returns the context for all actions performed in the application. getBaseContext() - if you want to access a context from another context in the application, you can access. getContext() - Returns a context view of only the currently running action.
What did I understand from what I read? -Nothing...

As I understand it, getApplicationContext() provides access to resources, calling an activity, etc. throughout the application, and I didn’t understand what it means to access the context from another context, but getContext () returns the context of the current action, and how do I find out what my current action is.
I'm confused, can you explain in a understandable language for a beginner? At the moment, if I need context somewhere, I turn to the one that is displayed first in the list (well, or at random), and I want to understand which one is needed in a given situation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-12-14
@foonfyrick

getApplicationContext is a Context method that returns the application class. If you extend Application and specify this class in the manifest, then getApplicationContext will return an object of this class.
getBaseContext() is a ContextWrapper method that returns the wrapped Context. The ContextWrapper wraps an arbitrary context and proxies its methods to somehow change the behavior.
getContext() is not a method of any context. It can be a View method, then it will return the context with which the view was created. For example, Activity or ContextThemeWrapper.
Or it can be a fragment method, then it will return the activity to which the fragment is currently attached.
Conclusion:
getApplicationContext() when you need to access the Application class, for example to implement a DI graph.
getBaseContext() when you need to access the base context (very, very rare. When it comes down to it, you will probably understand what you need).
getContext() when you need a context but only have a fragment/view.
PS Some rubbish is quoted in the question. Do not read books in Russian on android.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question