- Context
- ContextCompat
- What is Context in Android?
- Understanding Context by a Real World Example
- How Does This Work?
- Types of Context in Android
- Application Context
- getApplicationContext():
- Context в Android приложении
- Что такое Context?
- Контекст приложения
- Контекст Activity
- getContext() в ContentProvider
- Когда нельзя использовать getApplicationContext()?
- Правило большого пальца
- Understanding Context In Android Application
- What is Context in Android?
- Application Context
- Activity Context
- getContext() in ContentProvider
- When to use which Context?
- When not to use getApplicationContext() ?
- The Rule of Thumb
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 и выше.
Источник
What is Context in Android?
Android apps are popular for a long time and it is evolving to a greater level as user’s expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across a word context. So what exactly is this context and why is it so important? To answer this question lets first see what the literal meaning of context is:
The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood
Looking at this definition we come across two things:
- The context tells us about the surrounding information.
- It is very important to understand the environment which we want to understand.
Similarly when we talk about the Android Programming context can be understood as something which gives us the context of the current state of our application. We can break the context and its use into three major points:
- It allows us to access resources.
- It allows us to interact with other Android components by sending messages.
- It gives you information about your app environment.
In the official Android documentation, context is defined as:
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.
Understanding Context by a Real World Example
Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during the time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So here the room-service person is the context considering you are the single activity and the hotel to be your app, finally , the breakfast, lunch & dinner have to be the resources.
How Does This Work?
1. It is the context of the current/active state of the application.
Usually, the app got multiple screens like display/inquiry/add/delete screens(General requirement of a basic app). So when the user is searching for something, the context is an inquiry screen in this case.
2. It is used to get information about the activity and application.
The inquiry screen’s context specifies that the user is in inquiry activity, and he/she can submit queries related to the app
3. It is used to get access to resources, databases, and shared preferences, etc.
Via Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The context for the respective screen helps to get hold of database data and the shared data across screens
4. Both the Activity and Application classes extend the Context class.
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.
Types of Context in Android
There are mainly two types of context are available in Android.
- Application Context and
- Activity Context
The Overall view of the App hierarchy looks like the following:
It can be seen in the above image that in “Sample Application”, nearest Context is Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only.
Application Context
This context is tied to the life cycle of an application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext() . Some use cases of Application Context are:
- If it is necessary to create a singleton object
- During the necessity of a library in an activity
getApplicationContext():
It is used to return the context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a context and often we use “this” to pass the activity context or “getApplicationContext” to pass the application context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext() .
Источник
Context в Android приложении
Что такое Context?
Как следует из названия, это контекст текущего состояния приложения или объекта. Это позволяет вновь созданным объектам понять, что вообще происходит. Обычно его вызывают, чтобы получить информацию о другой части программы.
Кроме того, 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 или другого компонента, даже временно, используйте ссылку на контекст приложения.
Источник
Understanding Context In Android Application
What is Context in Android?
The Context in Android is actually the context of what we are talking about and where we are currently present. This will become more clear as we go along with this.
Few important points about the context:
- It is the context of the current state of the application.
- It can be used to get information regarding the activity and application.
- It can be used to get access to resources, databases, and shared preferences, and etc.
- Both the Activity and Application classes extend the Context class.
Context is almost everywhere in Android Development and it is the most important thing in Android Development, so we must understand to use it correctly.
Wrong use of Context can easily lead to memory leaks in an android application.
As there are different types of context in Android, we as an Android Developer often get confused about which context to use at which place. So let’s understand what are those, how to use those, and when to use which one.
Mainly two types of context:
- Application Context: It is the application and we are present in Application. For example — MyApplication(which extends Application class). It is an instance of MyApplication only.
- Activity Context: It is the activity and we are present in Activity. For example — MainActivity. It is an instance of MainActivity only.
If you are preparing for your next Android Interview, Join our Android Professional Course to learn the latest in Android and land job at top tech companies.
Application Context
It is an instance that is the singleton and can be accessed in activity via getApplicationContext() . This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.
Example Use: If you have to create a singleton object for your application and that object needs a context, always pass the application context.
If you pass the activity context here, it will lead to the memory leak as it will keep the reference to the activity and activity will not be garbage collected.
In case, when you have to initialize a library in an activity, always pass the application context, not the activity context.
You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal.
Activity Context
This context is available in an activity. This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.
Example Use: If you have to create an object whose lifecycle is attached to an activity, you can use the activity context.
The app hierarchy looks like the following:
- MyApplication [Here we have only Application context present] [Nearest Context is Application Context]
- MainActivity1 [Here we have both Activity(MainActivity1) context and Application context present] [Nearest Context is Activity Context]
- MainActivity2 [Here we have both Activity(MainActivity2) context and Application context present] [Nearest Context is Activity Context]
getContext() in ContentProvider
This context is the application context and can be used as the application context. You can get it using the getContext() method.
When to use which Context?
Let’s learn which context to use at which place with an example:
Suppose we have our class MyApplication(which extends the Application class). And, another class MyDB which is Singleton. And MyDB(which is Singleton) needs context. Which context will we be passing?
The answer is Application Context because if we pass the Activity Context (for example MainActivity1), even if MainActivity1 is not in use, the MyDB will be keeping the reference unnecessary which will lead to the memory leaks.
So always remember, in case of Singleton(lifecycle is attached to the application lifecycle), always use the Application Context.
So, now when to use the Activity Context. Whenever you are in Activity, for any UI operations like showing toast, dialogs, and etc, use the Activity Context.
Always try to use the nearest context which is available to you. When you are in Activity, the nearest context is Activity context. When you are in Application, the nearest context is the Application context. If Singleton, use the Application Context.
When not to use getApplicationContext() ?
- It’s not a complete Context , supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.
- It can create memory leaks if the Context from getApplicationContext() holds onto something created by your calls on it that you don’t clean up. With an Activity , if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process.
The Rule of Thumb
- In most cases, use the Context directly available to you from the enclosing component you’re working within. You can safely hold a reference to it as long as that reference does not extend beyond the lifecycle of that component. As soon as you need to save a reference to a Context from an object that lives beyond your Activity or Service, even temporarily, switch that reference you save over to the application context.
Reference: Stackoverflow. Thanks to the Stackoverflow community.
Источник