开源地址:https://github.com/square/leakcanary
FAQ : https://github.com/square/leakcanary/wiki/FAQ
配置
build.gradle
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
}
使用说明
建立RefWatcher全局变量
使用RefWatcher去监控引用,Activity,Fragment等中的内存泄漏
例子
第一步:定义RefWathcher全局变量
package com.app.client;
import android.app.Application;
import android.content.Context;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
public class MyApplication extends Application {
public static RefWatcher getRefWatcher(Context context){
MyApplication application = (MyApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
第二步:监控Activity中的内存泄漏问题
package com.app.client;
import android.app.Application;
import android.content.Context;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
public class MyApplication extends Application {
public static RefWatcher getRefWatcher(Context context){
MyApplication application = (MyApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
Manifest配置
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
第三步:生成的泄漏结果图
推荐的好文章:
【1】http://www.jianshu.com/p/0049e9b344b0
【2】http://blog.kamidox.com/android-memory-guide.html
【3】https://corner.squareup.com/2015/05/leak-canary.html
【4】http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/
【5】http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0510/2860.html