LeakCanary
提供了一种很便捷的方式,让咱们在开发阶段检测内存泄漏问题,咱们不须要本身去根据内存快照来分析内存泄漏的缘由,所须要作的仅仅是在Debug
包中集成它,它会自动地帮咱们检测内存泄漏,并给出致使泄漏的引用链。android
下面,就来看一下如何在项目当中集成它:bash
release
版本中,全部的调用都是空实现,这样就会避免在release
的版本中也在桌面生成一个泄漏检测结果的图标。dependencies {
//在 debug 版本中才会实现真正的功能
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
//在 release 版本中为空实现
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
复制代码
Application
,初始化一个全局RefWatcher
对象,它负责监视全部应当要被回收的对象:public class LeakCanaryApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
LeakCanaryApplication application = (LeakCanaryApplication) context.getApplicationContext();
return application.mRefWatcher;
}
}
复制代码
Activity
为例就须要在它的onDestory()
方法中加入监测的代码,咱们经过单例持有Activity
的引用,模拟了一种内存泄漏发生的场景:public class LeakSingleton {
private static LeakSingleton sInstance;
private Context mContext;
public static LeakSingleton getInstance(Context context) {
if (sInstance == null) {
sInstance = new LeakSingleton(context);
}
return sInstance;
}
private LeakSingleton(Context context) {
mContext = context;
}
}
public class LeakCanaryActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leak_canary);
//让这个单例对象持有 Activity 的引用
LeakSingleton.getInstance(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在 onDestroy 方法中使用 Application 中建立的 RefWatcher 监视须要回收的对象
LeakCanaryApplication.getRefWatcher(this).watch(this);
}
}
复制代码
在退出应用程序以后,咱们会发如今桌面上生成了一个新的图标,点击图标进入,就是LeakCanary
为咱们分析出的致使泄漏的引用链: 服务器
LeakCanary
集成到项目中的方法,下面,咱们来讨论一下它的实现原理。
当调用了RefWatcher.watch()
方法以后,会触发如下逻辑:app
KeyedWeakReference
,它内部引用了watch
传入的对象:final KeyedWeakReference reference = new KeyedWeakReference(watchedReference, key, referenceName, this.queue);
复制代码
this.watchExecutor.execute(new Runnable() {
public void run() {
RefWatcher.this.ensureGone(reference, watchStartNanoTime);
}
});
复制代码
GC
,假如引用仍是没有被清除,那么把当前的内存快照保存到.hprof
文件当中,并调用heapdumpListener
进行分析:void ensureGone(KeyedWeakReference reference, long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
long watchDurationMs = TimeUnit.NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
this.removeWeaklyReachableReferences();
if(!this.gone(reference) && !this.debuggerControl.isDebuggerAttached()) {
this.gcTrigger.runGc();
this.removeWeaklyReachableReferences();
if(!this.gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = TimeUnit.NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
File heapDumpFile = this.heapDumper.dumpHeap();
if(heapDumpFile == null) {
return;
}
long heapDumpDurationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
this.heapdumpListener.analyze(new HeapDump(heapDumpFile, reference.key, reference.name, watchDurationMs, gcDurationMs, heapDumpDurationMs));
}
}
}
复制代码
heapdumpListener
的实现类为ServiceHeapDumpListener
,它会启动内部的HeapAnalyzerService
:public void analyze(HeapDump heapDump) {
Preconditions.checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(this.context, heapDump, this.listenerServiceClass);
}
复制代码
IntentService
,所以它的onHandlerIntent
方法是运行在子线程中的,在经过HeapAnalyzer
分析完毕以后,把最终的结果传回给App
端展现检测的结果:protected void onHandleIntent(Intent intent) {
String listenerClassName = intent.getStringExtra("listener_class_extra");
HeapDump heapDump = (HeapDump)intent.getSerializableExtra("heapdump_extra");
AnalysisResult result = this.heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey);
AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
}
复制代码
HeapAnalyzer
会计算未能回收的引用到Gc Roots
的最短引用路径,若是泄漏,那么创建致使泄漏的引用链并经过AnalysisResult
返回:public AnalysisResult checkForLeak(File heapDumpFile, String referenceKey) {
long analysisStartNanoTime = System.nanoTime();
if(!heapDumpFile.exists()) {
IllegalArgumentException snapshot1 = new IllegalArgumentException("File does not exist: " + heapDumpFile);
return AnalysisResult.failure(snapshot1, this.since(analysisStartNanoTime));
} else {
ISnapshot snapshot = null;
AnalysisResult className;
try {
snapshot = this.openSnapshot(heapDumpFile);
IObject e = this.findLeakingReference(referenceKey, snapshot);
if(e != null) {
String className1 = e.getClazz().getName();
AnalysisResult result = this.findLeakTrace(analysisStartNanoTime, snapshot, e, className1, true);
if(!result.leakFound) {
result = this.findLeakTrace(analysisStartNanoTime, snapshot, e, className1, false);
}
AnalysisResult var9 = result;
return var9;
}
className = AnalysisResult.noLeak(this.since(analysisStartNanoTime));
} catch (SnapshotException var13) {
className = AnalysisResult.failure(var13, this.since(analysisStartNanoTime));
return className;
} finally {
this.cleanup(heapDumpFile, snapshot);
}
return className;
}
}
复制代码
默认LeakCanary
是会在桌面生成一个图标,点击图标以后,会展现致使泄漏的引用链,有时候,咱们但愿把这些信息上传到服务器中,那么就须要自定义收到结果后的处理的行为,下面,咱们看一下要怎么作:ide
DisplayLeakService
,进行本身的处理逻辑,这里咱们只是打印出泄漏的信息,heapDump
为对应的内存快照,result
为分析的结果,leakInfo
则是相关的信息:public class MyLeakUploadService extends DisplayLeakService {
@Override
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
Log.d("MyLeakUploadService", "leakInfo=" + leakInfo);
}
}
复制代码
Application
中初始化RefWatcher
的方式,第二个参数中传入咱们自定义的Service
类名:public class LeakCanaryApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = LeakCanary.install(this, MyLeakUploadService.class);
}
}
复制代码
AndroidManifest.xml
中注册自定义的Service
:<application>
<service android:name=".leakcanary.MyLeakUploadService"/>
</application>
复制代码
在调试阶段,咱们能够经过引入LeakCanary
,让它帮助咱们排查出一些会致使内存泄漏的问题。post