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

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

相关推荐
aningxiaoxixi17 分钟前
Android 之 audiotrack
android
枷锁—sha19 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
Cao_Shixin攻城狮4 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
呼啦啦呼啦啦啦啦啦啦7 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
idjl8 小时前
Mysql测试题
android·adb
游戏开发爱好者811 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
人生游戏牛马NPC1号11 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
星辰也为你祝福h13 小时前
Android原生Dialog
android
梁同学与Android14 小时前
Android ---【CPU优化】需要优化的原因及优化的地方
android
Misha韩14 小时前
React Native 基础tabBar和自定义tabBar - bottom-tabs
android·react native