Activity Context VS getApplicationContext(): When to use ?

shape
shape
shape
shape
shape
shape
shape
shape

Any Android developer has encountered the problem of having to use the Activity’s own reference instead of using getApplicationContext(). Both Activity and getApplicationContext() are instances of Context, but the difference is that Activity has the context of the Activity itself, and getApplicationContext() is the Context of the Application.

An Android application has several types of Context, such as:

  • Activity
  • Application
  • Service
  • BroadcastReceiver
  • ContentProvider

When to use Activity, getApplicationContext() and so on ?

After a bit of research, I found a table indicating when to use each case:

Application Activity Service ContentProvider BroadcastReceiver
Show a Dialog NO YES NO NO NO
Start an Activity NO1 YES NO1 NO1 NO1
Layout Inflation NO2 YES NO2 NO2 NO2
Start a Service YES YES YES YES YES
Bind to a Service YES YES YES YES NO
Send a Broadcast YES YES YES YES YES
Register BroadcastReceiver YES YES YES YES NO3
Load Resource Values YES YES YES YES YES

 

  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

Source: https://possiblemobile.com/2013/06/context/

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest news

Latest news directly from our blog.