Context in Android and Notes

Tram Ho

Hello everyone, today I would like to share about a fairly common topic in Android, which is Context. The purpose of this article somewhere new to Android can understand the true nature of Context, types of Context and more importantly, how to consider using them in each case in the most reasonable and accurate way, avoid causing unexpected errors.

1. Concepts

I would like to quote a passage from the Official Android Document about 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.

You can also understand the basics like this

Context is the state of the application at a given time.

Context is a basic class that contains most of the information about the android application environment, that is, all operations and interactions with the operating system must go through this class.

Context is an abstract class, it provides implementing classes with methods to access system and application resources. For example, it can initiate and run activities, broadcasts, intents, etc.

Now let’s look at the three most commonly used functions to access the Context:

  • getContext() — returns the Context associated with the called Activity.
  • getApplicationContext() — returns the Context associated with the Application containing all the Activities running within it.
  • getBaseContext() — related to the ContextWrapper, created around an existing Context and allowing its behavior to be changed. With getBaseContext() we can get the existing Context inside the ContextWrapper class.

Among these, the most prominent are getContext() and getApplicationContext() . Regarding getBaseContext() , there is a small caveat to avoid using this type of Context – this class is implemented when a class extends from ContextWrapper. This class has about 40 direct and indirect subclasses. Therefore, it is recommended to call directly to getContext, Activity, Fragment… to avoid causing memory leak.

2. Context . access types

2.1. getContext()

In getContext(), the Context is attached to an Activity and its lifecycle. We can think of Context as the layer behind the Activity and it will exist as long as the Activity exists. The moment the Activity dies, so does the Context.

Here is the list of functions that Activity’s Context provides us:

2.2. getApplicationContext()

In getApplicationContext(), our Context is tied to the application and its lifecycle. We can think of it as a layer behind the whole application. As long as the user doesn’t shut down the app, it persists.

Now you may be wondering, what is the difference between getContext() and getApplicationContext(). The difference is that the application Context is not related to the user interface. That means, we should not use it to Inflate a Layout, start an Activity as well as Dialog. As for the rest of the functions from the Activity Context, they are also available in the Application Context. So the list of functions for the Application Context includes the following:

3. How to properly use Context in Android

Using the right Context in Android is very important to ensure your app works properly and avoid problems like memoryleak or resource crashes. Here are some guidelines to help you use the right context:

  • Select a Context-Specific Context : Select a Context that provides the necessary scope for the operation you are performing. For example, if you are creating the UI component in an Activity, use the Activity Context instead of the Application Context.
  • Note the Lifespan of the Context : Consider the lifecycle of the component that requires the Context. For short-lived operations, use a Context that matches the Component’s Lifespan. For example, if you need the Context in the BroadcastReceiver’s onReceive() method, use the provided Context parameter instead of the persistent Context like the Application Context.
  • Avoid using a Context that works outside of its lifecycle : Be cautious when using a Context that works outside of the Activity’s lifecycle, as it can lead to memoryleak. For example, if you store a reference to the Activity Context and use it after the Activity has been destroyed, that can cause problems. In such cases, switch to using Application Context instead.
  • Memory Note : Avoid storing persistent references to Contexts unnecessarily, as they can hold a reference to the entire Activity and Application and prevent resources from being garbage collected. If you need a Context in a long-lived Component, such as a singleton, prefer using Application Context.
  • Consider Dependency Injection : Using Dependency Injections like Dagger, Hilt or Koin can simplify Context management by providing the right context when needed. It helps to decouple components and ensure the correct Context is injected based on the scope and requirements of the activity.

4. Conclusion

The choice of Context depends on the specific requirements of your code and the component you are dealing with. It is important to choose the right Context to avoid memoryleaks, resource issues, or inconsistencies in your application. As a general rule, try to use the most limited context possible to complete the current task, making sure it has the scope and Lifespan necessary for the operation.

Hope this article will be of some help to you. See you all in the next post.

Share the news now

Source : Viblo