性能優(yōu)化的幫助工具:
MAT,
Memory Monitor(屬于AndroidMonitor中一個模塊)怜械,
HeapTool(查看堆信息),
Allaction Tracking弄抬,
LeakCanary
Lint工具
1.Allaction Tracking
(1)追蹤
Allaction Tracking
在內存圖中點擊途中箭頭的部分茎辐,啟動追蹤,再次點擊就是停止追蹤掂恕,隨后自動生成一個alloc結尾的文件拖陆,這個文件就記錄了這次追蹤到的所有數(shù)據(jù),然后會在右上角打開一個窗口竹海。展示和第一種方式有點區(qū)別慕蔚,各有所長,他有兩種展現(xiàn)方式。
(2)分類我們的內存分配
生成的alloc文件
紅框中
Group by Method:用方法來分類我們的內存分配斋配,默認會以Group by Method來組織
Group by Allocator:用內存分配器來分類我們的內存分配
我們用 Group by Allocator的方式來查看一下孔飒。
可以看到我們自己包中灌闺,每一個類的內存分配次數(shù)和分配的大小。如果我們想看內存分配的實際在源碼中發(fā)生的地方坏瞄,可以選擇需要跳轉的對象桂对,點擊該按鈕就能發(fā)現(xiàn)我們的源碼。
(3)查看統(tǒng)計圖
想看某個圖層詳細內存分配鸠匀,則雙擊速表左鍵進入下一圖層
內存分配情況
通過[Layout方式查看更直觀
Layout方式
特別感謝
LooperJing
2.LeakCanary
(1)配置
Getting started
In your build.gradle:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.2'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.2'
}
In your Application class:
public class ExampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
// Normal app init code...
}
}
(2)制造一個單例內存泄漏的點
public class CommonUtils {
private static CommonUtils instance;
private Context context;
private CommonUtils(Context context) {
this.context = context;
}
public static CommonUtils getInstance(Context context) {
if (instance == null) {
instance = new CommonUtils(context);
}
return instance;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CommonUtils commonUtils = CommonUtils.getInstance(this);
}
(3)LeakCanary 發(fā)出內存泄漏通知
(4)LeakCanary 分析
LeakCanary 本質上還是用命令控制生成hprof文件分析檢查內存泄漏蕉斜。
3.Lint分析工具
Android Studio很方便,很好用缀棍,你可以試試點擊AS菜單欄上面的Analyze選項宅此,然后點擊Inspection Scope,然后選擇你需要檢測的范圍(比如整個項目)爬范,然后AS會自動彈出下圖所示的面板
lint分析展示面板
可能出現(xiàn)內存泄漏的類
檢測資源文件是否有沒有用到的資源父腕。
檢測常見內存泄露
安全問題SDK版本安全問題
是否有費的代碼沒有用到
代碼的規(guī)范---甚至駝峰命名法也會檢測
自動生成的羅列出來
沒用的導包
可能的bug