Fully understand Context in Android
Android application is using java, but not like java that you can create a class and main() function, then able to run. Android is based on components including Activity, Service, Content Provider and Broadcast receiver. You are not able to create a new component simply by using ‘new’ since all of these components have their own context. Activity extends from Context, Service and Application also extend from Context.
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
From source code, we can get the previous class diagram. ContextImpl is implementing all context abstract functions, and ContextWrapper wraps all functions from context and using ContextImpl class implementation. The attachBaseContext function is ContextWrapper class is making sure the context is attached only once. ContextThemeWrapper which as its name, apply theme from application or Activity which is defined as ‘android:theme’ in AndroidManifest.xml file. Since both Application and Service both do not need theme, so they inheritant directly from ContextWrapper. During the the activity, application and service are initiated, a new ContextImpl object will be created each time which implements the functions in Context.
How many Context in an Application?
From above, we can conclude that Number(Context)=Activity+Service+1(Application). For other components like Context Provider, Broadcast Receiver which are not subclass of Context. So they are not counted, but we need pass context object to them when create a new one.
What Context can do?
Context is powerful, but it still has some restrictions. Since context is implemented by ContextImpl, so in most situations we can use activity, service and application context in common. However, in some situation like start a Activity or pop up a dialog, it must use Activity context since a new Activity is based on another Activity to form a stack, also a popup dialog need to show on top of Activity except some system alert dialog.

Ways to get Context:
Difference between getApplication() and getApplicationContext()
Actually both functions return application object since application itself is a context. So why android provide two functions? The reason is because getApplication() is only able to be used in Activity and Service. In other components like BroadcastReceiver is only able to use getApplicationContext() to get application object.
Improper use of context can easily cause memory leak
Since Singleton will live a long time in the application which cause the context which is hold by it will not able to be GC.
What is Context in Android and which one should you use?
I find Context in Android, as one of the most difficult things to explain to anyone. When I started with Android development 2 years ago, I couldn’t wrap my head around the Context for a long period of time. I was so confused about it and yet I was using it on regular basis, simple because it is one of the fundamental things in Android. Still every time I needed to perform some operation that requires the Context, I felt anxious and I didn’t know how to “get” the right one.
Motivated by my confusion in early stages of my career as Android developer, I decided to express my understanding of Context and hope it will help someone who has just entered the world of Android and has no idea what does Context represent. Of course this article is also for anyone who wants to try to understand Context better. Now let’s get started.
In the official Android documentation here is how they defined Context.
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
At the beginning, this didn’t mean much to me. But as time passed, I started understanding its meaning.
Firstly, let’s look at 3 most used function for retrieving the Context:
- getContext() — returns the Context which is linked to the Activity from which is called,
- getApplicationContext() — returns the Context which is linked to Application which holds all activities running inside it,
- getBaseContext() —is related to ContextWrapper, which is created around existing Context and let us change its behavior. With getBaseContext() we can fetch the existing Context inside ContextWrapper class.
To understand core of the Context, we will focus on first two methods mentioned above, because getBaseContext() is based on understanding regular Context and ContextWrapper.
getContext()
In getContext(), Context is tied to an Activity and its lifecycle. We can imagine Context as layer which stands behind Activity and it will live as long as Activity lives. The moment the Activity dies, Context will too.
Activity’s Context has its own functionalities, which we can use for all sort of things Android framework supports. Here is the list of functionalities Activity’s Context provides us:
getApplicationContext()
In getApplicationContext(), our Context is tied to Application and its lifecycle. We can think of it as layer behind whole application. As long as user doesn’t kill the application, it’s alive.
You may wonder now, what is the difference between getContext() and getApplicationContext(). The difference is that Application’s Context is not UI related. It means that, we shouldn’t use it to Inflate a Layout, Start an Activity nor Show a Dialog. Regarding the rest of the functionalities from Activity’s Context, they are available from Application’s Context also. So the list of functionalities for Application’s Context looks like this:
Now that we checked the functionalities which different types of Context provide us, we can try to roughly describe its meaning. We can say the following
Context is a layer(interface) which stands behind its component (Activity, Application…) and component’s lifecycle, which provides access to various functionalities which are supported by application environment and Android framework.
The most used functionalities provided by Context are loading resources (such as strings, assets, themes…), starting Activities and Services and inflating layouts.
I hope by now you learnt something new and you understand Context a little bit better than you did before reading this article. Still, there is one more important thing which you need to consider when choosing the right Context.
One thing to pay attention when deciding which Context to choose
In this article, a lot of times was mentioned Context which is tied to component’s lifecycle. I would like to emphasize that this is important to consider because if you choose the wrong one, it can lead to memory leak, which can lead to breaking your app, which can lead to very very disappointing results.
The easiest way of showing you what do I mean by choosing the right Context, is by showing you an example.
Example
We have singleton (class which can have only 1 instance during the whole application lifecycle) ContextSingleton, which holds reference to a Context.
As you can see, our singleton hold the Context reference, but the thing is that our mContext could be any type of context, it could be Application’s or Activity’s. (there are more types of Context but in this article I chose to write only about Application and Activity one)
Why should I care?
Well, imagine you pass the Activity’s Context here. Our singleton, will contain reference to the Activity whose Context was passed. Aside from that, we know that our singleton will outlive the Activity. That will lead to Activity which won’t be garbage collected when killed, because it is referenced by ContextSingleton. This principal is going to lead to memory leak.
To solve this issue, we need to realize that our singleton has lifecycle similar to application’s one. Than it is trivial to conclude that by passing the Application’s Context in singleton, we will overcome this type of problem. To solve it, we just need to hold the reference of getApplicationContext() called from any context.
Conclusion
In this article I tried to express my way of understanding the Context in Android. We’ve also covered functionalities which provide Activity and Application Context, their difference and how you can decide which one you should use in different situations.
The goal of this article was to try to help new Android developers roughly understand what is Context in Android and why do we use it. There is still a lot more to learn regarding Context and its capabilities. For anyone who is trying to investigate more regarding Context, I can recommend this great article by Dave Smith.
I really hope that I brought you closer to understanding the Context in Android. If there were parts of article which you found hard to process, feel free to comment them. I’ll do my best to update the article depending on feedback.
Thank you for taking time to read my article.
Also I am always open for commenting on Android stuff, so if you feel like talking, contact me on twitter or linkedin.
Context в Android приложении

Как следует из названия, это контекст текущего состояния приложения или объекта. Это позволяет вновь созданным объектам понять, что вообще происходит. Обычно его вызывают, чтобы получить информацию о другой части программы.
Кроме того, Context является проводником в систему, он может предоставлять ресурсы, получать доступ к базам данных, преференсам и т.д. Ещё в Android приложениях есть Activity . Это похоже на проводник в среду, в которой выполняется ваше приложение. Объект Activity наследует объект Context . Он позволяет получить доступ к конкретным ресурсам и информации о среде приложения.
Context присутствует практически повсюду в Android приложении и является самой важной его частью, поэтому необходимо понимать, как правильно его использовать.
Неправильное использование Context может легко привести к утечкам памяти в Android приложении.
Существует много разных типов контекста, поэтому давайте разберёмся, что каждый из них представляет из себя, как и когда их правильно использовать.
Контекст приложения
Это singleton-экземпляр (единственный на всё приложение), и к нему можно получить доступ через функцию getApplicationContext() . Этот контекст привязан к жизненному циклу приложения. Контекст приложения может использоваться там, где вам нужен контекст, жизненный цикл которого не связан с текущим контекстом или когда вам нужно передать контекст за пределы Activity .
Например, если вам нужно создать singleton-объект для вашего приложения, и этому объекту нужен какой-нибудь контекст, всегда используйте контекст приложения.
Если вы передадите контекст Activity в этом случае, это приведет к утечке памяти, так как singleton-объект сохранит ссылку на Activity и она не будет уничтожена сборщиком мусора, когда это потребуется.
В случае, когда вам нужно инициализировать какую-либо библиотеку в Activity , всегда передавайте контекст приложения, а не контекст Activity .
Таким образом, getApplicationContext() нужно использовать тогда, когда известно, что вам нужен контекст для чего-то, что может жить дольше, чем любой другой контекст, который есть в вашем распоряжении.
Контекст Activity
Этот контекст доступен в Activity и привязан к её жизненному циклу. Контекст Activity следует использовать, когда вы передаете контекст в рамках Activity или вам нужен контекст, жизненный цикл которого привязан к текущему контексту.
getContext() в ContentProvider
Этот контекст является контекстом приложения и может использоваться аналогично контексту приложения. К нему можно получить доступ через метод getContext() .
Когда нельзя использовать getApplicationContext()?
- Это не полноценный контекст, поддерживающий всё, что может Activity . Некоторые вещи, которые вы попытаетесь сделать с этим контекстом, потерпят неудачу, в основном связанные с графическим интерфейсом.
- Могут появляться утечки памяти, если контекст из getApplicationContext() удерживается на каком-то объекте, который вы не очищаете впоследствии. Если же где-то удерживается контекст Activity , то как только Activity уничтожается сборщиком мусора, всё остальное тоже уничтожается. Объект Application остается на всю жизнь вашего процесса.
Правило большого пальца
В большинстве случаев используйте контекст, доступный непосредственно из компонента, в котором вы работаете в данный момент. Вы можете безопасно хранить ссылку на него, если она не выходит за пределы жизненного цикла этого компонента. Как только вам нужно сохранить ссылку на контекст в объекте, который живет за пределами вашей Activity или другого компонента, даже временно, используйте ссылку на контекст приложения.
Context
Context – это объект, который предоставляет доступ к базовым функциям приложения: доступ к ресурсам, к файловой системе, вызов активности и т.д. Activity является подклассом Context, поэтому в коде мы можем использовать её как ИмяАктивности.this (напр. MainActivity.this), или укороченную запись this. Классы Service, Application и др. также работают с контекстом.
Доступ к контексту можно получить разными способами. Существуют такие методы как getApplicationContext(), getContext(), getBaseContext() или this, который упоминался выше, если используется в активности.
На первых порах не обязательно понимать, зачем он нужен. Достаточно помнить о методах, которые позволяют получить контекст и использовать их в случае необходимости, когда какой-нибудь метод или конструктор будет требовать объект Context в своих параметрах.
В свою очередь Context имеет свои методы, позволяющие получать доступ к ресурсам и другим объектам.
- getAssets()
- getResources()
- getPackageManager()
- getString()
- getSharedPrefsFile()
Возьмём к примеру метод getAssets(). Ваше приложение может иметь ресурсы в папке assets вашего проекта. Чтобы получить доступ к данным ресурсам, приложение использует механизм контекста, который и отвечает доступность ресурсов для тех, кто запрашивает доступ — активность, служба и т.д. Аналогично происходит с методом getResources. Например, чтобы получить доступ к ресурсу цвета используется конструкция getResources().getColor(), которая может получить доступ к данным из файла res/colors.xml.
Таким образом, создавая, например, вторую активность, мы можем сразу обеспечить ей доступ к своим ресурсам, так как активность относится к контексту. При создании собственных компонентов View также используется контекст в конструкторах, так как компонент тоже может использовать ваши ресурсы. При создании собственных классов, если вам нужно будет обращаться к контексту, то необходимо создать конструктор:
Через контекст можно узнать практически всю информацию о вашем приложении — имя пакета, класса и т.п.
Тем не менее, следует различать контекст в разных ситуациях. Допустим, у вас есть приложение с несколькими активностями. В манифесте можно прописать используемую тему как для всего приложения, так и для каждой активности в отдельности. Соответственно, выбор контекста повлияет на результат. Как правило, при использовании собственной темы предпочтительнее использовать контекст активности, а не приложения.
Очень часто начинающие программисты впадают в ступор, когда ключевое слово this не работает в анонимных классах, например, при щелчке кнопки. В этом случае, используйте полное имя класса перед ним.
При создании адаптеров для списков также обращаются к контексту.
Или ещё пример для адаптера в фрагменте ListFragment:
Здесь тоже следует быть внимательным, если используется своя тема для списка.
Последнее замечание относится к опытным программистам. Неправильный контекст может послужить источником утечки памяти. Если вы создадите собственный класс, в котором содержится статическая переменная, обращающая к контексту активности, то система будет держать ссылку на переменную. Если активность будет закрыта, то сборщик мусора не сможет очистить память от переменной и самой неиспользуемой активности. В таких случаях лучше использовать контекст приложения через метод getApplicationContext().
ContextCompat
В библиотеки совместимости появился свой класс для контекста ContextCompat. Он может вам пригодиться, когда студия вдруг подчеркнёт метод в старом проекте и объявит его устаревшим.
Допустим, мы хотим поменять цвет текста на кнопки.
Студия ругается, что нужно использовать новый вариант getColor(int, Theme). Заменим строчку.
Если посмотреть на исходники этого варианта, то увидим, что там тоже идёт вызов нового метода. Поэтому можно сразу использовать правильный вариант, если вы пишете под Marshmallow и выше.