Android 车载性能优化-内存泄漏

内存监测工具

Android Studio 自带工具 Profiler

排查泄露的出处主要有两处:

  • CoroutineScope(Dispatchers.Main) 协程未释放
  • 匿名内部类对外部类有强引用

协程未释放

kotlin 复制代码
// CoroutineScope 未在 destroy 方法中 cancel
fun recycleViewScrollZoo() {
    LogUtils.i(TAG, "recycleViewScrollZoo")
    CoroutineScope(Dispatchers.Main).launch{
        FlowBus.events.collect{ event ->
            when(event){
                is EventWidget -> {
                    LogUtils.i(TAG, "recycleViewScrollZoo event.widgetName = : ${event.widgetName}")
                    scrollByWidgetName(event.widgetName)
                }
            }
        }
    }
}

造成内存泄漏的情况

选择一个类,可以查看具体的泄漏对象

解决方案

找到泄漏对象,在 destroy 方法中 cancel 任务

匿名内部类

kotlin 复制代码
private val mainHandler = Handler(Looper.getMainLooper())

// 匿名内部类
private val launcherStyleObserver = object : ContentObserver(mainHandler) {

    override fun onChange(selfChange: Boolean, uri: Uri?) {
        super.onChange(selfChange, uri)
        if (uri != null && uri.toString() == Settings.Global.getUriFor(KEY_LAUNCHER_STYLE)
                .toString()
        ) {
            startHomeWhenInBackGround()
            updateLauncherStyle()
        }
    }
}

匿名内部类持有外部类的引用,修改代码如下:

kotlin 复制代码
private val launcherStyleObserver = LauncherStyleObserver(mainHandler, this)
// 使用静态内部类和弱引用:将匿名内部类改为静态内部类,并使用弱引用持有外部类的引用
private class LauncherStyleObserver(handler: Handler, activity: MainActivity) : ContentObserver(handler) {

    // 弱引用
    private val activityReference = WeakReference(activity)
    override fun onChange(selfChange: Boolean, uri: Uri?) {
        super.onChange(selfChange, uri)
        val activity = activityReference.get()
        if (uri != null && uri.toString() == Settings.Global.getUriFor(KEY_LAUNCHER_STYLE)
                .toString()
        ) {
            activity?.startHomeWhenInBackGround()
            activity?.updateLauncherStyle()
        }
    }
}

解决方案:使用静态内部类和弱引用,将匿名内部类改为静态内部类,并使用弱引用持有外部类的引用

相关推荐
vocal1 小时前
【我的安卓第一课】Android 多线程与异步通信机制(1)
android
顾林海1 小时前
ViewModel 销毁时机详解
android·面试·android jetpack
恋猫de小郭3 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
@Ryan Ding3 小时前
MySQL主从复制与读写分离概述
android·mysql·adb
移动开发者1号4 小时前
Android 同步屏障(SyncBarrier)深度解析与应用实战
android·kotlin
移动开发者1号4 小时前
深入协程调试:协程调试工具与实战
android·kotlin
雨白12 小时前
Jetpack系列(三):Room数据库——从增删改查到数据库平滑升级
android·android jetpack
花王江不语15 小时前
android studio 配置硬件加速 haxm
android·ide·android studio
江太翁17 小时前
mediapipe流水线分析 三
android·mediapipe
与火星的孩子对话18 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip