Activity Lifecycle
1. Giới thiệu
Activity Lifecycle là vòng đời của một Activity, từ khi được tạo đến khi bị hủy.
2. Các trạng thái Lifecycle
┌──────────────┐
│ Created │
└──────┬───────┘
│ onCreate()
▼
┌──────────────┐
│ Started │
└──────┬───────┘
│ onStart()
▼
┌──────────────┐
┌──────────▶│ Resumed │◀──────────┐
│ └──────┬───────┘ │
│ │ onPause() │
│ ▼ │
│ ┌──────────────┐ │
│ │ Paused │ │
│ └──────┬───────┘ │
│ │ onStop() onRestart()
│ ▼ │
│ ┌──────────────┐ │
│ │ Stopped │───────────┘
│ └──────┬───────┘
│ │ onDestroy()
│ ▼
│ ┌──────────────┐
└───────────│ Destroyed │
└──────────────┘3. Lifecycle Callbacks
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
// Khởi tạo UI, biến, data binding
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart")
// Activity đang hiển thị
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
// Activity ở foreground, tương tác được
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause")
// Activity mất focus (dialog, app khác)
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop")
// Activity không còn hiển thị
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
// Activity bị hủy, cleanup resources
}
override fun onRestart() {
super.onRestart()
Log.d(TAG, "onRestart")
// Từ stopped -> started
}
}4. Lifecycle với Compose
@Composable
fun MyScreen() {
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> {
Log.d("MyScreen", "Screen resumed")
}
Lifecycle.Event.ON_PAUSE -> {
Log.d("MyScreen", "Screen paused")
}
else -> {}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
// UI content
}5. LifecycleScope
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Coroutine tự động cancel khi Activity destroyed
lifecycleScope.launch {
val data = fetchData()
updateUI(data)
}
// Chỉ chạy khi resumed
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
viewModel.uiState.collect { state ->
updateUI(state)
}
}
}
}
}6. Các tình huống phổ biến
Mở Activity mới
Activity A: onPause()
Activity B: onCreate() -> onStart() -> onResume()
Activity A: onStop()Nhấn Back từ B về A
Activity B: onPause()
Activity A: onRestart() -> onStart() -> onResume()
Activity B: onStop() -> onDestroy()Xoay màn hình (Configuration Change)
onPause() -> onStop() -> onDestroy()
onCreate() -> onStart() -> onResume()Nhấn Home
onPause() -> onStop()Quay lại từ Home
onRestart() -> onStart() -> onResume()7. Lưu trữ State
savedInstanceState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val counter = savedInstanceState?.getInt("counter") ?: 0
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("counter", counter)
}rememberSaveable trong Compose
@Composable
fun Counter() {
var count by rememberSaveable { mutableStateOf(0) }
Button(onClick = { count++ }) {
Text("Count: $count")
}
}8. ViewModel survive Configuration Change
class MainViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
// ViewModel survive configuration changes
// Data không bị mất khi xoay màn hình
}
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val state by viewModel.uiState.collectAsState()
MainScreen(state)
}
}
}9. Best Practices
// ✅ Khởi tạo nhanh trong onCreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { ... } // Chỉ setup UI
}
// ✅ Start resources trong onStart/onResume
override fun onResume() {
super.onResume()
locationManager.startUpdates()
}
// ✅ Stop resources trong onPause/onStop
override fun onPause() {
super.onPause()
locationManager.stopUpdates()
}
// ❌ Tránh heavy work trong lifecycle callbacks
// Dùng ViewModel + Coroutines thay thế📝 Tóm tắt
| Callback | Khi nào |
|---|---|
| onCreate | Activity được tạo |
| onStart | Activity hiển thị |
| onResume | Activity tương tác được |
| onPause | Activity mất focus |
| onStop | Activity không hiển thị |
| onDestroy | Activity bị hủy |
| onRestart | Từ stopped → started |
Last updated on