1. 前言
眾所周知,Android開發(fā)過程中,內(nèi)存是非常重要的,但是項目上線后經(jīng)常會有低概率的OOM的錯誤,及內(nèi)存溢出。內(nèi)存溢出原因很多,可能加載圖片過大,但是大部分原因是存在內(nèi)存泄漏。之前檢測內(nèi)存泄漏一直用mat,但是這個工具使用起來比較麻煩,大部分人寧可選擇忽視低概率的oom導(dǎo)致的crash。(mat使用方法:http://blog.csdn.net/dfskhgalshgkajghljgh/article/details/50513985)現(xiàn)在LeakCanary的出現(xiàn)使得定位內(nèi)存泄漏變得異常簡單。
LeakCanary對應(yīng)github地址:https://github.com/square/leakcanary
2.使用方法
1)在項目的build.gradle文件添加:
debugCompile'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
可以看到,debugCompile跟releaseCompile 引入的是不同的包, 在 debug 版本上,集成 LeakCanary 庫,并執(zhí)行內(nèi)存泄漏監(jiān)測,而在 release 版本上,集成一個無操作的 wrapper ,這樣對程序性能就不會有影響。
2)在Application類添加:
public class LCApplication 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...
}
}
LeakCanary.install() 會返回一個預(yù)定義的 RefWatcher,同時也會啟用一個 ActivityRefWatcher,用于自動監(jiān)控調(diào)用 Activity.onDestroy() 之后泄露的 activity。
如果是簡單的檢測activity是否存在內(nèi)存泄漏,上面兩個步驟就可以了,是不是很簡單。
那么當(dāng)某個activity存在內(nèi)存泄漏的時候,會有什么提示呢?LeakCanary會自動展示一個通知欄,點開提示框你會看到引起內(nèi)存溢出的引用堆棧信息。
3..其他功能
上面提到,LeakCanary.install() 會返回一個預(yù)定義的 RefWatcher,同時也會啟用一個 ActivityRefWatcher,用于自動監(jiān)控調(diào)用 Activity.onDestroy() 之后泄露的 activity?,F(xiàn)在很多app都使用到了fragment,那fragment如何檢測呢。
1)Application 中獲取到refWatcher對象。
public class LCApplication extends Application {
public static RefWatcher refWatcher;
@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;
}
refWatcher = LeakCanary.install(this);
// Normal app init code...
}
}
2)使用 RefWatcher 監(jiān)控 Fragment:
public abstract class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = LCApplication.refWatcher;
refWatcher.watch(this);
}
}
這樣則像監(jiān)聽activity一樣監(jiān)聽fragment。其實這種方式一樣適用于任何對象,比如圖片,自定義類等等,非常方便。
github地址:https://github.com/square/leakcanary