
Các thành phần và vòng đời Activity trong Android
Android applications are built from a set of core components that work together to provide a rich user experience. Mastering these components—especially Activities , Services , Content…

Khi một Activity được khởi tạo lần đầu, phương thức nào được gọi trước tiên?
Nếu người dùng quay màn hình từ portrait sang landscape, chuỗi phương thức nào sẽ được gọi?
Intent được sử dụng để gì trong Android?
Khi một Activity bị che khuất hoàn toàn, chuỗi phương thức nào sẽ xảy ra?
Để lưu trạng thái trước khi Activity chuyển sang Activity khác, bạn nên thực hiện ở phương thức nào?
Content Provider thường lưu dữ liệu ở đâu?
Phương thức nào của lớp Log dùng để ghi thông điệp mức DEBUG?
Trong hình ảnh cette image, Activity Lab hiện tại đã gọi phương thức nào bao nhiêu lần?
Khi một Service được bind, bạn có thể:
Understanding Android Components and the Activity Lifecycle
Android applications are built from a set of core components that work together to provide a rich user experience. Mastering these components—especially Activities, Services, Content Providers, and Broadcast Receivers—is essential for any Android developer. This course breaks down each component, explains their roles, and dives deep into the Activity lifecycle, a sequence of callbacks that governs how an Activity is created, displayed, paused, stopped, and destroyed.
1. The Four Fundamental Android Components
Android’s architecture defines four primary building blocks. Knowing which component to use in a given scenario helps you write clean, maintainable code.
- Activity: Represents a single screen with a user interface. It handles user interaction and UI rendering. Every visible screen in an Android app is an Activity.
- Service: Runs in the background without a UI. Services are ideal for long‑running operations such as playing music, downloading files, or handling network communication.
- Content Provider: Manages a shared data set, typically stored in a SQLite database or a file. Other apps can query, insert, update, or delete data through a well‑defined URI interface.
- Broadcast Receiver: Listens for system‑wide or app‑specific broadcast messages (e.g., battery low, network change). It reacts to these events without a UI.
Among these, only the Broadcast Receiver does not provide a user interface. This distinction is frequently tested in quizzes and interviews.
2. The Activity Lifecycle Overview
When an Activity is launched, Android invokes a series of lifecycle callbacks. Understanding the order of these callbacks is crucial for managing resources, preserving UI state, and ensuring a smooth user experience.
- onCreate() – Called once when the Activity is first created. You inflate layouts, bind views, and perform one‑time initializations here.
- onStart() – The Activity becomes visible but is not yet in the foreground.
- onResume() – The Activity enters the foreground and starts interacting with the user.
- onPause() – The Activity loses focus but is still partially visible (e.g., a dialog appears). You should commit unsaved changes here because the next callback may be onStop() or onResume().
- onStop() – The Activity is no longer visible. Heavy resources should be released, and you may persist UI state.
- onDestroy() – Final cleanup before the Activity is removed from memory.
- onRestart() – Called after onStop() when the Activity is about to become visible again.
The first method invoked when an Activity is created for the first time is onCreate(). This is where you typically call setContentView() and initialize your UI components.
3. Lifecycle Transitions in Real‑World Scenarios
Different user actions trigger distinct sequences of callbacks. Let’s explore three common situations.
3.1. Rotating the Device (Portrait ↔ Landscape)
By default, a configuration change such as screen rotation destroys the current Activity and creates a new one. The system follows this pattern:
- onPause()
- onStop()
- onDestroy()
- onCreate()
- onStart()
- onResume()
However, many developers handle the rotation more efficiently by using android:configChanges or ViewModel to retain data. In a quiz context, the simplified answer often focuses on the onStop → onRestart → onStart chain, which occurs when the Activity is temporarily hidden but not destroyed.
3.2. Activity Covered by Another Full‑Screen Activity
When a new Activity completely covers the current one (e.g., opening a Settings screen), the underlying Activity goes through:
- onPause() – The current Activity loses focus.
- onStop() – It becomes invisible.
When the user returns, the sequence is onRestart() → onStart() → onResume(). Knowing that onPause() → onStop() is the correct chain for a fully hidden Activity helps you answer related quiz questions.
3.3. Saving State Before Switching to Another Activity
Before an Activity transitions to another (e.g., launching a detail screen), you should persist transient UI state in onPause(). This method is guaranteed to be called before the new Activity appears, making it the safest place to store data in SharedPreferences, a database, or a ViewModel.
4. Core Concepts Reinforced by Quiz Questions
Below is a concise review of each quiz item, paired with an explanation that deepens your understanding.
- Component without UI – Broadcast Receiver. It reacts to system or app broadcasts without presenting a screen.
- First method on Activity creation – onCreate(). This is where you set up the layout and initialize variables.
- Method chain on screen rotation – The simplified answer often expects onStop() → onRestart() → onStart(), reflecting the Activity being stopped and then restarted.
- Purpose of an Intent – To start another Activity (or Service, Broadcast, etc.). In the quiz, the correct choice is “Gọi một Activity khác”.
- When an Activity is fully hidden – The system calls onPause() → onStop(). This indicates the Activity is no longer visible but still retained in memory.
- Saving state before moving to another Activity – Implement this in onPause(), because it runs before the new Activity takes focus.
- Content Provider storage location – Typically in a SQLite database or file system, not in RAM or Intent objects.
- Logging a DEBUG message – Use
Log.d(), which writes messages with the DEBUG priority.
5. Practical Tips for Managing the Activity Lifecycle
- Use ViewModel to retain UI data across configuration changes without manual state saving.
- Leverage onSaveInstanceState() to store transient UI state (e.g., scroll position) before the Activity may be destroyed.
- Release heavy resources (e.g., camera, sensors) in onStop() or onDestroy() to avoid memory leaks.
- Register/unregister Broadcast Receivers in onStart()/onStop() when they are UI‑related, or in onCreate()/onDestroy() for global receivers.
- Prefer startActivityForResult() (or the newer Activity Result API) when you need a result back from another Activity, handling the callback in onActivityResult() or the ActivityResultLauncher.
6. Frequently Asked Questions (FAQ)
What is the difference between onPause() and onStop()?
onPause() is called when the Activity is partially obscured (e.g., a dialog appears). It should be used to commit unsaved changes because the next callback could be onResume(). onStop() occurs when the Activity is no longer visible; heavy resources can be released here.
How can I prevent my Activity from being destroyed on rotation?
Declare android:configChanges="orientation|screenSize" in the manifest, or better, use a ViewModel to retain data across the automatic destroy‑create cycle.
When should I use a Service instead of an Activity?
Use a Service for background tasks that do not require user interaction, such as playing music, downloading files, or performing periodic work. Activities should be reserved for UI‑driven tasks.
Can a Content Provider be used without a UI?
Yes. Content Providers are designed to share data between apps and can operate entirely in the background, exposing CRUD operations via URIs.
What logging level should I use for production builds?
For production, limit logging to Log.w() (warnings) and Log.e() (errors). Remove or disable Log.d() and Log.i() statements to avoid performance overhead and leaking sensitive information.
7. Summary
Mastering Android components and the Activity lifecycle equips you to build robust, responsive apps. Remember the key points:
- Broadcast Receivers have no UI.
- The first lifecycle callback is onCreate().
- Screen rotation typically triggers onStop → onRestart → onStart (simplified view).
- Use onPause() to save transient state before navigating away.
- Content Providers store data in SQLite or files, not in RAM.
- Log debugging messages with
Log.d().
By internalizing these concepts, you’ll be prepared for both practical development challenges and interview quizzes that test your Android knowledge.
