You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端Lottie动画未正常释放内存问题求助

Android Lottie动画内存泄漏:清理后仍OOM的解决方法

我在Android应用中使用Lottie动画时遇到内存问题:即使在onDestroy中执行了取消、清除动画等操作,Lottie仍未正常释放内存,长期运行会导致Java堆内存持续增长,最终触发OOM错误。当前的清理代码如下:

override fun onDestroy() {
  super.onDestroy()

  binding.lottieAnimation.apply {
    cancelAnimation()
    clearAnimation()
    removeAllAnimatorListeners()
    removeAllUpdateListeners()
    invalidate()
 }
   LottieCompositionFactory.clearCache(this@MyActivity)    
}

Android Memory Profiler显示Java堆内存占用持续增长:
内存分析器截图

以下是针对性的解决步骤:

  • 完善LottieView的核心清理逻辑
    现有代码缺少断开Composition引用的关键步骤,这是Lottie资源无法释放的常见原因。需要补充以下操作:

    binding.lottieAnimation.apply {
      cancelAnimation()
      clearAnimation()
      // 移除所有类型的监听器
      removeAllAnimatorListeners()
      removeAllUpdateListeners()
      removeAllLottieOnCompositionLoadedListeners()
      // 断开Composition引用,释放核心资源
      setComposition(null)
      invalidate()
      // 若使用的是LottieDrawable,需调用recycle()
      (drawable as? LottieDrawable)?.recycle()
    }
    
  • 彻底清理缓存
    LottieCompositionFactory.clearCache()默认清理全局缓存,但如果你的动画加载时指定了自定义缓存Key,需要额外移除对应Key的缓存:

    // 假设加载时用了自定义key:LottieCompositionFactory.fromAsset(context, "anim.json", "custom_key")
    LottieCompositionFactory.removeComposition("custom_key")
    // 再清理全局缓存
    LottieCompositionFactory.clearCache()
    

    部分新版本Lottie的LottieAnimationView提供了destroy()方法,直接调用可一键清理内部资源:

    binding.lottieAnimation.destroy()
    
  • 排查隐性引用持有
    用Memory Profiler生成堆转储(Heap Dump),查找LottieComposition、LottieAnimationView等实例的引用链,确认是否存在以下情况:

    • 全局单例、ViewModel持有了Lottie相关对象的引用
    • 未移除的匿名监听器(比如addAnimatorListener时用了匿名内部类,持有Activity引用)
  • 升级Lottie版本
    旧版本Lottie存在已知的内存泄漏bug,建议升级到最新稳定版(如v6.0.0及以上),官方在后续版本中修复了大量内存泄漏问题。

  • 优化动画加载策略

    • 对重复使用的动画,用全局缓存统一管理,但要在App退到后台或页面销毁时主动清理
    • 非循环动画设置repeatCount = 0,避免动画持续运行导致资源无法释放

内容的提问来源于stack exchange,提问作者alexC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:12:37