Leakcanary簡介
我們經常被OOM所困擾,引起OOM往往都是內存泄漏長期沒有解決造成的,如果在對象的生命週期本該結束的時候,這個對象還被一系列的引用,這就會導致內存泄漏,隨着泄漏的累積,app將消耗完內存,直到OOM,LeakCanary 是一個開源的在debug版本中檢測內存泄漏的java庫。下面介紹其使用方法:
在eclipse中使用
1.下載爲eclipse優化的Leakcanary,下載鏈接 http://download.csdn.net/detail/wo_ha/9755042;
2. 將項目導入eclipse中;
3. 將Leakcanary作爲自己項目的依賴庫(右鍵單擊自己的項目—–>Properties—–>Android—–>在Libary選擇Add—–>選擇導入的Leakcanary項目—–>Apply—–>OK),若出現V4包報錯,請選擇其中一個項目的V4包去替換另一個項目的V4包,參考http://blog.csdn.net/jackrex/article/details/8984033;
4. 在自己項目的AndroidManifest中添加權限和相關的Activity、Service;
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<activity
android:name="com.squareup.leakcanary.internal.DisplayLeakActivity"
android:enabled="false"
android:icon="@drawable/__leak_canary_icon"
android:label="@string/__leak_canary_display_activity_label"
android:taskAffinity="com.squareup.leakcanary"
android:theme="@style/__LeakCanary.Base" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.squareup.leakcanary.internal.HeapAnalyzerService"
android:enabled="false"
android:process=":leakcanary" />
<service
android:name="com.squareup.leakcanary.DisplayLeakService"
android:enabled="false" />
5.自定義一個 Application;
public class ExampleApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
別忘在AndroidManifest的Application節點添加name哦
6.在需要觀察的Activity的Destory方法添加如下代碼;
@Override
protected void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = ExampleApplication.getRefWatcher(this);
refWatcher.watch(this);
}
好啦,把Leakcanary集成到我們的eclipse項目中就完成了,如果有內存泄漏如下圖,本講解例子的源碼:http://download.csdn.net/detail/wo_ha/9755057
在Android Studio中使用
這可比在eclipse中使用簡單多了,只需要在需要的Mode的gradle中添加如下代碼在同步下就可以了,使用的方法都是一樣的,我就不貼代碼了
dependencies {
.......
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'
}