What is Context?
Context is like a passport or ID card for your app. It gives your code access to resources, databases, preferences, and lets you communicate with the Android system.
Think of it like this:
-
You're in a hotel (Android System)
-
Context is your room key card
-
With this key card, you can:
-
Access your room (resources)
-
Use hotel services (system services)
-
Order room service (start activities)
-
Get information about the hotel (app info)
-
Why Do We Need Context?
Without Context, you cannot:
- Access resources (strings, images, colors from XML)
- Start activities
- Access databases
- Get system services (WiFi, Location, etc.)
- Show toasts or dialogs
- Access preferences
- Create views
Example - Without Context:
// ❌ This will NOT work - no context!
String appName = getString(R.string.app_name); // ERROR!
Toast.makeText("Hello"); // ERROR! Needs context
Example - With Context:
// ✅ This works!
String appName = context.getString(R.string.app_name);
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
Types of Context
There are mainly two types of Context:
1. Application Context
2. Activity Context
Let me explain both in detail:
1. Application Context
What it is: Context tied to the entire application's lifecycle
How long it lives: From app start to app end (the whole time your app is running)
When to use:
- When you need context that lives as long as the application
- For singletons (objects that exist once in the entire app)
- For loading resources
- For accessing application-level operations
How to get it:
Context appContext = getApplicationContext();
// OR
Context appContext = getApplication();
Real-world examples:
// 1. Creating a singleton database
public class DatabaseHelper {
private static DatabaseHelper instance;
public static DatabaseHelper getInstance(Context context) {
if (instance == null) {
// Use Application Context - lives forever
instance = new DatabaseHelper(context.getApplicationContext());
}
return instance;
}
}
// 2. Registering broadcast receivers that should work app-wide
Context appContext = getApplicationContext();
appContext.registerReceiver(myReceiver, intentFilter);
// 3. Loading resources
String appName = getApplicationContext().getString(R.string.app_name);
2. Activity Context
What it is: Context tied to an Activity's lifecycle
How long it lives: Only while the activity is alive (onCreate to onDestroy)
When to use:
- When you need context tied to an activity
- For showing UI elements (Dialogs, Toasts related to activity)
- For starting new activities
- For inflating layouts
How to get it:
Context activityContext = this; // Inside an Activity
// OR
Context activityContext = ActivityName.this;
Real-world examples:
// 1. Showing a dialog (needs activity context)
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Warning")
.setMessage("Are you sure?")
.show();
// 2. Starting a new activity
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
// 3. Inflating a layout
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.my_layout, null);
Application Context vs Activity Context - Key Differences
| Feature | Application Context | Activity Context |
|---|---|---|
| Lifespan | Entire app lifetime | Only during activity lifetime |
| Use for UI | Not recommended | Yes |
| Show Dialogs | No (will crash) | Yes |
| Start Activities | Needs FLAG_ACTIVITY_NEW_TASK | Yes, naturally |
| Inflate Layouts | Possible but not recommended | Yes |
| Load Resources | Yes | Yes |
| Singletons | Yes (prevents memory leaks) | No (causes memory leaks) |
| Register Receivers | For long-lived receivers | For activity-specific receivers |
Common Mistakes & Memory Leaks
WRONG - Causes Memory Leak:
public class MainActivity extends AppCompatActivity {
// Static reference to activity context
private static Context context; // BAD!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Storing activity context in static variable
context = this; // MEMORY LEAK!
}
}
Why is this bad?
- Static variables live forever
- Activity context should die when activity is destroyed
- Now the activity can't be garbage collected
- Memory leak!
CORRECT - No Memory Leak:
public class MainActivity extends AppCompatActivity {
// Use Application Context for static references
private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use Application Context
context = getApplicationContext(); // SAFE!
}
}
Context is like a bridge between your code and the Android system. It's your app's identity card that gives you permission to:
- Access resources
- Use system services
- Start activities
- Store data
- And much more!
Remember:
- Application Context = Long-lived (whole app)
- Activity Context = Short-lived (one screen)
- Choose wisely to avoid memory leaks and crashes!