# Android 内存泄漏排查实战:从 LeakCanary 报警到根因定位
线上突然收到 OOM 崩溃告警,内存曲线持续上涨不回落,用户反馈"用久了就卡"。这种场景下,内存泄漏往往是第一嫌疑人。本文从一次真实的泄漏排查过程出发,讲清楚如何用 LeakCanary 快速定位泄漏源,以及常见泄漏场景的根因与修复手法。
集成 LeakCanary 后,打开应用几分钟就弹出通知:
┬───
│ GC Root: Local variable in thread
│
├─ android.os.HandlerThread instance
│ thread name: 'LeakCanary-Heap-Dump'
│
├─ android.os.Handler instance
│
├─ com.example.ui.HomeActivity$1 (anonymous class)
│ holding MainActivity instance
│
╰→ com.example.ui.HomeActivity instance
Leaking: YES (Activity#mDestroyed=true)关键信息: 1. 泄漏对象:HomeActivity 实例 2. GC Root:匿名内部类持有 Activity 引用 3. 泄漏原因:Activity 已销毁(mDestroyed=true),但仍被 Handler 持有
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ❌ 匿名内部类持有外部 Activity 引用
Handler(Looper.getMainLooper()).postDelayed({
findViewById(R.id.tvTitle).text = "更新"
}, 10000)
// 用户 3 秒后退出 Activity,但 Handler 消息 10 秒后才执行
// Activity 实例被 Handler 持有 7 秒无法回收
}
}1. Lambda 或匿名内部类会隐式持有外部类(Activity)的引用 2. Handler 消息队列持有 Runnable 3. Activity 销毁时,消息未执行完,Activity 无法被 GC
方案 A:静态内部类 + 弱引用
class HomeActivity : AppCompatActivity() {
private val handler = SafeHandler(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handler.sendEmptyMessageDelayed(1, 10000)
}
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacksAndMessages(null) // 清空消息队列
}
class SafeHandler(activity: HomeActivity) : Handler(Looper.getMainLooper()) {
private val activityRef = WeakReference(activity)
override fun handleMessage(msg: Message) {
activityRef.get()?.apply {
findViewById(R.id.tvTitle).text = "更新"
}
}
}
}方案 B:Lifecycle 感知的 Handler(推荐)
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
delay(10000)
if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
findViewById(R.id.tvTitle).text = "更新"
}
}
}
}object ImageLoader {
private var context: Context? = null
fun init(context: Context) {
this.context = context // ❌ 如果传入 Activity,单例会一直持有
}
fun loadImage(url: String, view: ImageView) {
context?.let {
Glide.with(it).load(url).into(view)
}
}
}// Activity 中调用 ImageLoader.init(this) // ❌ 传入 Activity Context
1. 单例生命周期 = 应用生命周期 2. 持有 Activity Context 后,Activity 无法释放 3. 内存中可能存在多个已销毁的 Activity 实例
object ImageLoader {
private lateinit var appContext: Context
fun init(context: Context) {
// ✅ 转为 ApplicationContext
this.appContext = context.applicationContext
}
fun loadImage(url: String, view: ImageView) {
// Glide.with() 会自动处理生命周期
Glide.with(view.context).load(url).into(view)
}
}核心原则: - 单例、静态变量只持有 `ApplicationContext` - 需要 Activity Context 的场景,通过参数传入,不存储
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ❌ 非静态内部类持有外部 Activity
DataTask().execute()
}
inner class DataTask : AsyncTask<Void, Void, String>() {
override fun doInBackground(vararg params: Void?): String {
Thread.sleep(10000) // 模拟耗时操作
return "result"
}
override fun onPostExecute(result: String) {
// Activity 可能已销毁,但仍被 Task 持有
findViewById(R.id.tvResult).text = result
}
}
}class MainActivity : AppCompatActivity() {
private var job: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ✅ 使用 lifecycleScope,自动取消
job = lifecycleScope.launch {
val result = withContext(Dispatchers.IO) {
delay(10000)
"result"
}
findViewById(R.id.tvResult).text = result
}
}
override fun onDestroy() {
super.onDestroy()
job?.cancel() // 手动取消也可
}
}class ProfileActivity : AppCompatActivity() {
private val viewModel: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ❌ 使用 observeForever,未在 onDestroy 中移除
viewModel.userLiveData.observeForever { user ->
findViewById(R.id.tvName).text = user.name
}
}
}- `observeForever` 不会自动移除观察者 - LiveData 持有 Observer,Observer 持有 Activity
class ProfileActivity : AppCompatActivity() {
private val viewModel: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ✅ 使用 observe(lifecycleOwner),自动清理
viewModel.userLiveData.observe(this) { user ->
findViewById(R.id.tvName).text = user.name
}
}
}class ImageActivity : AppCompatActivity() {
private var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bitmap = BitmapFactory.decodeResource(resources, R.drawable.large_image)
findViewById(R.id.ivImage).setImageBitmap(bitmap)
// ❌ Activity 销毁时未回收 Bitmap
}
}class ImageActivity : AppCompatActivity() {
private var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bitmap = BitmapFactory.decodeResource(resources, R.drawable.large_image)
findViewById(R.id.ivImage).setImageBitmap(bitmap)
}
override fun onDestroy() {
super.onDestroy()
bitmap?.recycle() // ✅ 手动回收
bitmap = null
}
}更好的方案:使用 Glide/Coil 等图片库,自动管理生命周期。
dependencies {
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.12'
}无需其他配置,debug 包自动启用。
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.config = LeakCanary.config.copy(
retainedVisibleThreshold = 3, // 保留 3 个对象后才触发 dump
dumpHeap = true,
dumpHeapWhenDebugging = false, // 调试时不 dump
leakingObjectFinder = FilteringLeakingObjectFinder(
AndroidObjectInspectors.appLeakingObjectFilters
)
)
}
}LeakCanary.config = LeakCanary.config.copy(
referenceMatchers = AndroidReferenceMatchers.appDefaults +
IgnoredReferenceMatcher(
pattern = "com.android.internal.policy.DecorView.mContext"
)
)1. 集成 LeakCanary:debug 包自动检测 2. 复现场景:打开关键页面,退出,等待通知 3. 分析 Trace:找到 GC Root → 泄漏对象的引用链 4. 定位代码:查看持有引用的类(匿名类/单例/静态变量) 5. 修复验证:修改后重新测试,确认不再报警 6. 线上监控:接入性能监控平台(Firebase Performance / 腾讯 Matrix)
| 场景 | 泄漏原因 | 修复方案 | |------|---------|---------| | Handler 延时任务 | 匿名类持有 Activity | 静态类+弱引用 / lifecycleScope | | 单例持有 Context | 单例生命周期 > Activity | 使用 ApplicationContext | | AsyncTask / Thread | 非静态内部类 | 静态类+弱引用 / Coroutine | | LiveData observeForever | 未移除观察者 | 使用 observe(lifecycleOwner) | | 事件监听器未注销 | 全局 EventBus/监听器 | onDestroy 中反注册 | | Bitmap 未回收 | 大对象占用内存 | onDestroy 中 recycle() | | WebView 未清理 | WebView 持有 Activity | onDestroy 中 destroy() |
// 测试环境手动触发
LeakCanary.dumpHeap()class MyFragment : Fragment() {
override fun onDestroy() {
super.onDestroy()
// 检测自定义对象是否泄漏
AppWatcher.objectWatcher.watch(
watchedObject = customObject,
description = "CustomObject should be GC'd"
)
}
}androidTestImplementation 'com.squareup.leakcanary:leakcanary-android-instrumentation:2.12'@Test
fun testNoLeaks() {
val scenario = launchActivity()
scenario.close()
// 断言无泄漏
val leaks = LeakCanary.detectLeaks()
assertThat(leaks).isEmpty()
}内存泄漏排查的核心是理解对象生命周期:
- Activity/Fragment 生命周期短,不应被长生命周期对象持有 - 匿名类/非静态内部类会隐式持有外部类引用 - 异步任务/监听器/观察者需要在合适时机清理 - 使用 Jetpack 组件(ViewModel/LiveData/Coroutine)可自动处理大部分场景
LeakCanary 是快速定位的利器,但真正的修复需要理解引用链和生命周期关系。养成"谁创建谁清理"的习惯,大部分泄漏都能在编码阶段避免。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。