0%

安卓内存管理原理与实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
在安卓开发中,内存管理是应用稳定性和性能的关键。了解安卓内存结构、垃圾回收机制和内存优化技巧,可以帮助开发者写出高效、低耗的应用,避免 ANR(应用无响应)和 OOM(内存溢出)问题。

1️⃣ 安卓内存结构概览

安卓应用运行在 Android Runtime (ART) 上,每个应用进程独立,内存主要分为以下几部分:

内存区域 描述
Dalvik/ART 堆(Heap) 存储应用对象,受垃圾回收管理
栈(Stack) 存储方法调用、局部变量,随线程创建和销毁
Native 内存 C/C++ 层分配的内存,如 Bitmap、OpenGL 资源
共享库/内存映射 加载系统库和 APK 资源
内存映射文件(Mapped Files) APK、dex、so 文件映射内存

💡 小技巧:使用 Android Studio Profiler → Memory 可以实时查看各区域内存占用情况。

2️⃣ 垃圾回收机制(GC)

安卓内存管理的核心是 ART 的垃圾回收:

2.1 垃圾回收策略

ART 主要使用 分代 + 并发 GC:

年轻代(Young Generation):

存储短生命周期对象

使用 Copying GC,清理效率高

老年代(Old Generation):

存储长生命周期对象

使用 Mark-Sweep-Compact GC,减少碎片

大对象(如大 Bitmap):

直接分配在老年代或 Native 内存

2.2 GC 类型
类型 特点 适用场景
Serial GC 单线程,简单 小内存设备
Parallel GC 多线程 多核设备
Concurrent GC 并发执行,减少停顿 UI 主线程敏感应用
3️⃣ 内存泄漏与分析
3.1 内存泄漏常见场景

Activity/Fragment 持有 Context 导致无法回收

Handler/Thread 持有外部引用

静态集合存储对象

Bitmap 或 Drawable 未回收

3.2 内存泄漏工具

LeakCanary:实时检测内存泄漏

Memory Profiler:可视化对象分配、堆快照

MAT (Memory Analyzer Tool):分析复杂堆内存

示例使用 LeakCanary:

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
if (LeakCanary.isInAnalyzerProcess(this)) return
LeakCanary.install(this)
}
}


当 Activity 或对象未被回收时,LeakCanary 会弹出警告。

4️⃣ 内存优化实战
4.1 避免内存泄漏

使用 弱引用(WeakReference) 或 软引用(SoftReference)

避免在静态变量中持有 Context

Activity/Fragment 使用 ViewBinding 时注意解绑

4.2 控制对象创建

重复使用对象池(如 BitmapPool)

减少临时对象创建,尤其在 RecyclerView/循环里

4.3 图片/资源优化

使用 BitmapFactory.Options.inSampleSize 降低内存占用

Glide 或 Coil 自动处理缓存和复用

4.4 内存监控
val runtime = Runtime.getRuntime()
Log.d("Memory", "Max: ${runtime.maxMemory()/1024/1024}MB")
Log.d("Memory", "Total: ${runtime.totalMemory()/1024/1024}MB")
Log.d("Memory", "Free: ${runtime.freeMemory()/1024/1024}MB")


maxMemory:应用可用最大堆

totalMemory:已申请堆

freeMemory:堆中可用空间

5️⃣ 案例:Bitmap 内存优化
// 原始加载大图,容易 OOM
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.large_image)

// 优化:采样缩放
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeResource(resources, R.drawable.large_image, options)
options.inSampleSize = 4 // 缩小 4 倍
options.inJustDecodeBounds = false
val optimizedBitmap = BitmapFactory.decodeResource(resources, R.drawable.large_image, options)

6️⃣ 总结

安卓内存管理核心点:

了解内存结构:Heap、Stack、Native 内存

掌握 GC 原理:年轻代、老年代、并发回收

避免内存泄漏:Context、Handler、静态引用注意

优化对象创建:复用、对象池、图片压缩

实时监控:Profiler、LeakCanary

内存优化不仅提升性能,还能提升用户体验,降低崩溃率。掌握这些原理,你的应用会更稳定、更流畅。