Context in Android

What is Context? 

            A Context provides access to information about the application state. It provides Activities, Fragments, and Services access to resource files, images, theme/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.

What is a Context used for?

  • Explicitly starting a component (activity and services) 
  • Creating a View
  • Sending a broadcast
  • Retrieving a System Service
  • Access to information about the application state

Application Context

            It is an instance which is the singleton and can be accessed in an 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 an activity.

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.

Application Context vs Activity Context

            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. 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.

Comments

Popular posts from this blog

Android Process States

Android Overview

Android App Overview