Context, Application & Manifest Flashcards
ANDROID › System
- What is a Context in Android and what does it provide?
- An abstract class that is the handle to the app's environment. It gives access to resources, assets, system services (getSystemService), package info, file/SharedPreferences storage, and the ability to start activities, services, and broadcasts.
- What is the key difference between Application context and Activity context?
- Application context is a single instance tied to the process lifetime; Activity context is tied to a single Activity's lifecycle and is also a themed UI context. Use Activity context for UI (inflation, dialogs, theming) and Application context for long-lived, process-scoped objects.
- Why does holding an Activity context in a singleton cause a memory leak?
- The singleton outlives the Activity, so the strong reference keeps the Activity (and its whole view tree and resources) from being garbage collected after it is destroyed (e.g. on rotation). Use applicationContext or a WeakReference instead.
- Why can't you use the Application context to inflate UI or show a dialog?
- The Application context is not a themed/UI context, so it lacks the Activity's theme and window token. Inflating themed views or showing a Dialog with it gives wrong styling or a BadTokenException; use an Activity context for UI.
- What is the Application class and when is its onCreate called?
- The base class for global app state, instantiated once per process before any component. Its onCreate runs on the main thread before the first Activity/Service, so heavy or blocking work there delays cold start and can cause ANRs.
- How do you observe every Activity's lifecycle from one place?
- Call registerActivityLifecycleCallbacks() on the Application with an ActivityLifecycleCallbacks implementation. It is commonly used for analytics, crash context, and app foreground/background detection.
- What problem does the AndroidX App Startup library solve?
- It replaces multiple library-defined ContentProviders (each one slow to instantiate at launch) with a single InitializationProvider, and initializes components in a deterministic, dependency-ordered way, improving startup time.
- What do the two methods of the App Startup Initializer interface do?
- create(context) builds and returns the component instance; dependencies() returns the list of other Initializers that must run first. The library resolves the graph and initializes dependencies before dependents.
- Name the four app component types that must be declared in the manifest.
- Activities (<activity>), Services (<service>), BroadcastReceivers (<receiver>), and ContentProviders (<provider>). An undeclared activity, service, or provider cannot be started; receivers may also be registered at runtime in code.