Qualquer desenvolvedor Android já se deparou com o problema de ter que usar a referência da própria Activity ao invés de usar getApplicationContext(). Tanto Activity e getApplicationContext() são instâncias de Context, porém a diferença é que Activity possui o contexto da própria Activity, e getApplicationContext() é o Context da Aplicação.
Uma aplicação Android possui diversos tipos de Context, tais como:
- Activity
- Application
- Service
- BroadcastReceiver
- ContentProvider
Quando utilizar Activity, getApplicationContext() e etc ?
Depois de pesquisar um pouco, encontrei uma tabela indicando quando utilizar cada caso:
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 |
- 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.
- 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.
- Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.
Fonte: https://possiblemobile.com/2013/06/context/