跳到主要内容

Android Activity / Fragment 生命周期

🔄 深刻理解 Android 生命周期是避免内存泄露、状态丢失和 UI 异常的基础。

Activity 生命周期

onCreate → onStart → onResume(Activity 可交互)

onPause → onStop → onDestroy(Activity 销毁)

关键回调说明

回调觧发时机常见操作
onCreate首次创建初始化 View、ViewModel、数据绑定
onStart变为可见注册广播接收器
onResume开始前台恢复动画、相机预览
onPause失去焦点暫停动画、保存未提交数据
onStop不再可见释放重量级资源
onDestroy即将销毁释放所有资源

旋转屏幕时的生命周期

旋转时: onPause → onStop → onDestroy
新方向: onCreate → onStart → onResume

保存/恢复状态:
onSaveInstanceState(在 onStop 前)

onRestoreInstanceState(在 onStart 后)

Fragment 生命周期

onAttach → onCreate → onCreateView → onViewCreated
→ onViewStateRestored → onStart → onResume

onPause → onStop → onSaveInstanceState → onDestroyView
→ onDestroy → onDetach

Fragment View 异于 Fragment 本身

class MyFragment : Fragment() {
// viewBinding 在 onDestroyView 时设为 null
private var _binding: FragmentMyBinding? = null
private val binding get() = _binding!!

override fun onCreateView(inflater: LayoutInflater, ...) =
FragmentMyBinding.inflate(inflater).also { _binding = it }.root

override fun onDestroyView() {
super.onDestroyView()
_binding = null // 防止内存泄露内存泄露
}
}

ViewModel 与生命周期

class MyViewModel : ViewModel() {
val uiState = MutableStateFlow(UiState())

// 旋转屏幕不会销毁 ViewModel
// 只有 Activity 最终关闭才调用 onCleared()
override fun onCleared() {
super.onCleared()
// 释放异步任务
}
}

// 在 Activity 中获取 ViewModel
class MyActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
}

常见内存泄露场景

// 错误:静态引用 Context
object MyManager {
var context: Context? = null // 会持有 Activity 导致泄露
}

// 正确:使用 applicationContext
object MyManager {
lateinit var appContext: Context
fun init(context: Context) {
appContext = context.applicationContext // 安全
}
}

常见误区

  • onPause 中做耗时操作,导致切换应用延迟
  • Fragment 在 onDestroyView 后不置空 binding,导致内存泄露
  • 在 ViewModel 中持有 View 或 Context 引用