不断学习,做更好的自己!
视频号 | CSDN | 简书 |
---|---|---|
欢迎打开微信,关注我的视频号:程序员朵朵 | 点我 | 点我 |
使用 MAT 来分析内存问题,有一些门槛,会有一些难度,并且效率也不是很高,对于一个内存泄漏问题,可能要进行多次排查和对比才能找到问题的原因。为了能简单迅速的发现内存泄漏,Square 公司基于 MAT 开源了 LeakCanary
1. 在 app/build.gradle 中加入引用:
dependencies {
//在 debug 版本中才会实现真正的功能
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
//在 release 版本中为空实现
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
}
2. 在 Application 中:
public class MyApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = setupLeakCanary();
}
private RefWatcher setupLeakCanary(){
if (LeakCanary.isInAnalyzerProcess(this)) {
return mRefWatcher.DISABLED;
}
return LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
MyApplication leakApplication = (MyApplication) context.getApplicationContext();
return leakApplication.mRefWatcher;
}
}
3. 在需要回收的对象上,添加检测代码。
LeakSingleton.java
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;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//让这个单例对象持有 Activity 的引用
LeakSingleton.getInstance(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在 onDestroy 方法中使用 Application 中创建的 RefWatcher 监视需要回收的对象
MyApplication.getRefWatcher(this).watch(this);
}
}
在退出应用程序之后,我们会发现在桌面上生成了一个新的图标,点击图标进入,就是LeakCanary为我们分析出的导致泄漏的引用链:
当调用了 RefWatcher.watch() 方法之后,会触发以下逻辑:
final KeyedWeakReference reference = new KeyedWeakReference(watchedReference, key, referenceName, this.queue);
this.watchExecutor.execute(new Runnable() {
public void run() {
RefWatcher.this.ensureGone(reference, watchStartNanoTime);
}
});
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));
}
}
}
public void analyze(HeapDump heapDump) {
Preconditions.checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(this.context, heapDump, this.listenerServiceClass);
}
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);
}
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 中文使用说明