Context refers to the state in which Android components are running. It is used to instantiate and communicate between components. There are two main types of context: UI context and non-UI context. UI context includes activities and fragments, and allows components to be themed. Non-UI context includes services and receivers run without UI. It is important to use the correct context for each situation to avoid crashes or memory leaks.
2. What we know about
contexts ?
Simplest definition would be ....
Context is STATE, in which android components are
currently running.
3. Context used for...
We use it to instantiate, access components and communicate
between components.
➔ Your own app components:
Activity,Fragment, Service and so on...
➔ Android system components:
Context is used for getting system components like PackageManager,
WifiManager, BluetoothManger like
context.getSystemService(Context.BLUETOOTH_SERVICE);
➔ Your and Other App components:
Communicating between your own components and other app’s
components is almost identical if you use the intent-filter approach.
4. Types of contexts ?
In Android, context can be broadly divided into
1. UI-Context
2. Non-UI-Context.
5. UI- Context
ContextThemeWrapper is the only UI context in Android.
Activity extends the ContextThemeWrapper, hence when we inflate any XML
with UI context, our views get themed.
ContextThemeWrapper = Ui context + Theme
Catch: view.getContext() does not always give you UI-context back, because
view can get inflated with Non-UI context too. Using Non-UI context means
your UI will not get themed
UI Context is
- In Activity:
Instance of your activity (this)
- In Fragment:
getContext() in Fragment
- In View:
getContext()(WhenView was inflated using UI-Context)
6. Non-UI Context
Any instance other than ContextThemeWrapper is the Non UI context in
Android.
Non-UI Context is
- Application instance as context
- In Activity:
getApplicationContext()
- In Broadcast Receiver:-
Context received in broadcast receiver.
- In Service:-
Instance of your service (this) and getApplicationContext()
- Context:-
getApplicationContext()
7. When to use which
context ?
If you use context in wrong place you get the embarrassment of
application crash or memory leak. Trust me we all gone through it.
Smart answer to smart question is:
If you need to create UI components- Use UI Context; eg. Creating
dialogs or else use Non-UI context.
Remember never pass short living context to long living components.
Do not use Application context just in fear of memory leak or possible
UI issues. You know by now what will you lose if you use application
context everywhere.