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()
        }
    }
}

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

相关推荐
AFinalStone18 分钟前
Android 7系统无障碍服务(四)AccessibilityEvent 的产生与投递
android·无障碍服务
智购科技无人售货机工厂35 分钟前
2026自动售货机热敏打印模块集成:从串口驱动到小票自动裁切的工程实践~YH
android·stm32·单片机·嵌入式硬件·系统架构
A13345551 小时前
苹果安卓手机播放器推荐:2026无广告4K怎么选
android·智能手机
hunterandroid3 小时前
ContentProvider 跨进程数据共享实战
android·前端
天空之城--3 小时前
Android输入法子系统深度解析
android
天空之城--5 小时前
Android全链路性能优化:从原理到实践的终极指南
android·性能优化
Meteors.5 小时前
Android 性能优化:05.CPU优化
android·性能优化
石头猫灯6 小时前
一次 CMS 被黑实录:完整事件思路梳理
android·学习
zhonyu鱼6 小时前
Escrcpy:用电脑键盘鼠标操作安卓手机的跨平台投屏工具
android·计算机外设·电脑
千里马学框架6 小时前
安卓开机性能优化:如何安全高效地裁剪 SystemService
android·智能手机·framework·wms·手机·性能·车载