Android application context vs activity context

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 или другого компонента, даже временно, используйте ссылку на контекст приложения.

Источник

Using Context

A Context provides access to information about the application state. It provides Activities, Fragments, and Services access to resource files, images, themes/styles, and external directory locations. It also enables access to Android’s built-in services, such as those used for layout inflation, keyboard, and finding content providers.

In many cases when the «context is required», we simply need to pass in the instance of the current activity. In situations where we are inside objects created by the activity such as adapters or fragments, we need to pass in the activity instance into those objects. In situations where we are outside of an activity (in an application or service), we can use the «application» context instead.

Below are a few use cases that require a Context object.

When explicitly starting a component, two pieces of information are required:

  • package name, which identifies the application that contains the component.
  • fully-qualified Java class name for the component.
Читайте также:  Android notification button click

If starting an internal component, the context can be passed in since the package name of the current application can be extracted through context.getPackageName() .

Contexts contain the following information that views require:

  • device screen size and dimensions for converting dp,sp to pixels
  • styled attributes
  • activity reference for onClick attributes

We use the context to fetch the LayoutInflater in order to inflate an XML layout into memory:

We use the context to fetch the LocalBroadcastManager when sending out or registering a receiver for a broadcast:

To send notifications from an application, the NotificationManager system service is required:

Refer to the list of all available system services that can be retrieved through a Context.

While themes and styles are usually applied at the application level, they can be also specified at the Activity level. In this way, the activity can have a different set of themes or styles than the rest of the application (e.g. if the ActionBar needs to be disabled for certain pages). You will notice in the AndroidManifest.xml file that there is typically an android:theme for the application. We can also specify a different one for an Activity:

For this reason, it’s important to know that there is an Application Context and an Activity Context, which last for the duration of their respective lifecycle. Most Views should be passed an Activity Context in order to gain access to what themes, styles, dimensions should be applied. If no theme is specified explicitly for the Activity, the default is to use the one specified for the application.

In most cases, you should use the Activity Context. Normally, the keyword this in Java references the instance of the class and can be used whenever Context is needed inside an Activity. The example below shows how Toast messages can be displayed using this approach:

When using anonymous functions when implementing listeners, the keyword this in Java applies to the most immediate class being declared. In these cases, the outer class MainActivity has to be specified to refer to the Activity instance.

When constructing adapters for a ListView, typically getContext() is usually called during the layout inflation process. This method usually uses the context that instantiated the ArrayAdapter:

If you instantiate the ArrayAdapter with the application context, however, you are likely to notice that the themes/styles are not being applied. For this reason, make sure you are passing in the Activity context in these cases.

Whereas an ArrayAdapter requires a context to be passed into it’s constructor, a RecyclerView.Adapter does not. Instead, the correct context can be inferred from the parent view when inflation is necessary.

The associated RecyclerView always passes itself as the parent view into the RecyclerView.Adapter.onCreateViewHolder() call.

If a context is needed outside of the onCreateViewHolder() method, as long as there’s a ViewHolder instance available, a context can be retrieved via: viewHolder.itemView.getContext() . itemView is a public, non-null, and final field in the base ViewHolder class.

The Application Context is typically used when singleton instances need to be created, such as a custom manager class that requires Context information to gain access to system services but gets reused across multiple Activities. Since retaining a reference to the Activity context would cause memory not to be reclaimed after it is no longer running, it’s important to use the Application Context instead.

In the example below, if the context being stored is an Activity or Service and it’s destroyed by the Android system, it won’t be able to be garbage collected because the CustomManager class holds a static reference to it.

To avoid memory leaks, never hold a reference to a context beyond its lifecycle. Check any of your background threads, pending handlers, or inner classes that may be holding onto context objects as well.

The right way is to store the application context in CustomManager.getInstance() . The application context is a singleton and is tied to the lifespan of application’s process, making it safe to store a reference to it.

Use the application context when a context reference is needed beyond the lifespan of a component, or if it should be independent of the lifecycle of the context being passed in.

Читайте также:  Аимп для телефонов андроидов

Источник

Different ways to get Context in Android

Context is one of the important and most used property. You need Context to perform a lot of things on Android. Be is displaying a toast or Accessing database, you use context a lot while building Android app.

Context is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. It contains information about what Views are there, How they are laid out etc.

So, it is important to know different types of Context and methods you can call to get context. Lets get started.

The “this” Keyword

The this keyword in general sense refers to current class instance. So, when use “this” keyword inside an Activity, it refers to that Activity instance. And as Activity is subclass of “Context”, you will get context of that activity.

If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or this@MainActivity (Kotlin)

Get current activity context : View.getContext()

This method can be called on a View like textView.getContext() . This will give the context of activity in which the view is currently hosted in.

Get App-level context : getApplicationContext()

If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. you can use this.

So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application.

You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext()

Get Original context : getBaseContext()

This method is only useful when you are using ContextWrapper. You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext()

( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context)

Get Context from Fragment : getContext()

When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in.

Get parent Activity : getActivity()

You can get the parent activity from a Fragment by calling getActivity() .

💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context. Except for some cases, for example when using ContextWrapper, getContext() and getActivity() can point to different contexts.

Non-nullable Context : requireContext() and requireActivity()

These methods are same but “NotNull” versions of getContext() and getActivity() respectively. Usually, if a fragment is detached from Activity, you will get “null” value when you call getContext() or getActivity() . So even when you are sure the context won’t be null, you still have to add null checks (especially in Kotlin) because they return Nullable type.

But requireContext() and requireActivity() will throw IllegalStateException instead of returning null, if there is no context.

These methods are mainly useful when you using Kotlin and you need a Non-Nullable Context. So using these methods instead, is matter of personal preference.

So, did you learn something new? If you did, please clap and share the post. 😄

Источник

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.
Читайте также:  Penalty shootout для андроид

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.

  1. Application Context and
  2. 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() .

Источник

Оцените статью