# 内存优化思路
[TOC]
## 内存优化的重点
1. Activity的内存泄露
2. Bitmap的内存抖动
3. Thread的管理
## 内存泄露优化步骤
1. 检测是否存在Activity泄露
打开App,尽可能多的进入应用的每一个Activity,然后退出App,保留应用在后台
执行命令:
```
adb shell dumpsys meminfo com.daigou.sg.debug -d
```
输出格式如下:
```
Applications Memory Usage (in Kilobytes):
Uptime: 1035026617 Realtime: 1037698240
** MEMINFO in pid 31260 [com.daigou.sg.debug] **
Pss Private Private SwapPss Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 52309 52180 44 0 71680 61003 10676
Dalvik Heap 4488 4316 12 0 9015 2871 6144
Dalvik Other 2448 2448 0 0
Stack 152 152 0 0
Ashmem 90 80 0 0
Other dev 141 0 140 0
.so mmap 5082 304 2968 55
.apk mmap 1808 0 552 0
.ttf mmap 420 0 400 0
.dex mmap 17818 4 16152 0
.oat mmap 488 0 40 0
.art mmap 10238 9352 432 1
Other mmap 399 4 308 0
GL mtrack 54812 54812 0 0
Unknown 5741 5668 60 11
TOTAL 156501 129320 21108 67 80695 63874 16820
App Summary
Pss(KB)
------
Java Heap: 14100
Native Heap: 52180
Code: 20420
Stack: 152
Graphics: 54812
Private Other: 8764
System: 6073
TOTAL: 156501 TOTAL SWAP PSS: 67
Objects
Views: 172 ViewRootImpl: 1
AppContexts: 4 Activities: 2
Assets: 4 AssetManagers: 3
Local Binders: 37 Proxy Binders: 35
Parcel memory: 15 Parcel count: 59
Death Recipients: 3 OpenSSL Sockets: 4
WebViews: 0
SQL
MEMORY_USED: 485
PAGECACHE_OVERFLOW: 196 MALLOC_SIZE: 117
DATABASES
pgsz dbsz Lookaside(b) cache Dbname
4 28 87 65/45/8 /data/user/0/com.daigou.sg.debug/databases/google_analytics_v4.db
4 17436 26 47/19/2 /data/user/0/com.daigou.sg.debug/databases/chuck.db
```
这里主要管理Objects栏的Activities,理论上来说,当应用完全退出时,不应该再有Activities在内存中了,但是 现在我们发现依然存在2个,说明应用存在内存泄露
那么,如何找到泄露的这两个Activity呢,很简单,借助我们的
```
adb shell am dumpheap com.daigou.s![](https://i.vgy.me/1PgMNR.png)![](https://i.vgy.me/JbuAZ7.png)g.debug /data/local/tmp/memoryheap.hprof
```
![](https://i.vgy.me/k6kNRr.png)