LeakCanary
- 有時候OOM只是表象,更深層次的原因可能是內存泄漏,什麼是內存泄漏?直白點說就是該內存空間使用完之後沒有被回收,內存泄漏嚴重會導致內存很快被耗盡,從而導致OOM,最後程序crash~~~
- LeakCanary可以檢測內存泄漏,讓內存泄漏無所遁形。使用後,在debug模式下,如果出現內存泄漏,則會彈出通知,告訴你哪裏出現了泄漏,非常好用~
- github源碼
- LeakCanary使用說明
- LeakCanary中文使用說明
- build.gradle 中加入引用,不同的編譯使用不同的引用.目前已經到1.4版本了,具體見 github
dependencies { debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' forTestCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' }
-
簡單示例:
public class MyApplication extends MultiDexApplication { private RefWatcher mRefWatcher; @Override public void onCreate() { super.onCreate(); // init memory leak detection mRefWatcher = LeakCanary.install(this); } public static RefWatcher getRefWatcher(Context context) { MyApplication application = (MyApplication) context.getApplicationContext(); return application.mRefWatcher; } } //監控你想要監控的對象。以此爲例: public class BaseFragment extends RxFragment { @Override public void onDestroy() { super.onDestroy(); if (getActivity() != null) { RefWatcher refWatcher = ZYApplication.getRefWatcher(getActivity()); refWatcher.watch(this); } } }