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

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

相关推荐
厮年断弦16 分钟前
AI 辅助开发实录:一周做完一个 Android 本地音乐播放器,这些坑替你踩了
android
hai_android32 分钟前
InputStage 责任链核心执行流程
android·android studio·android jetpack
mmsx3 小时前
Android 测绘计算工程化:七四参数、高程拟合与单位系统
android·kotlin
我是场5 小时前
我的NPI项目之-Touch的EE特性
android·arm开发
天空之城--5 小时前
Android一周动态:AI编程、Compose与车载生态新信号
android·flutter
恋猫de小郭6 小时前
Dart 4.0 要彻底移除 dart:mirrors,Augmentations 应该要来了
android·前端·flutter
Carson带你学Android8 小时前
Gemini 4 Argon 发布:对 Android 开发者意味着什么?
android·ai编程
事圆则缓9 小时前
Kotlin Flow、StateFlow、SharedFlow 全解析:冷流、热流与 Android 状态管理
android·kotlin·php
应用市场9 小时前
把旧 Pixel 变成相册备份中转站(上):Mac 到安卓的照片传输工具设计——流式上传、sha256 校验、adb forward 与 Bonjour
android·macos·adb·kotlin·swift
墨天梦9 小时前
B08_Fragment事务通信与双生命周期
android