LeakCanary提供了一种很方便的方式,让咱们在开发阶段测试内存泄露,咱们不须要本身根据内存块来分析内存泄露的缘由,咱们只须要在项目中集成他,而后他就会帮咱们检测内存泄露,并给出内存泄露的引用链java
implementation 'com.squareup.leakcanary:leakcanary-android:1.5.1'
复制代码
public class App extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
mRefWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
App application = (App) context.getApplicationContext();
return application.mRefWatcher;
}
}
复制代码
public class ActivityOne extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 100000);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
复制代码
public abstract class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = App.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
复制代码
经过监听Activity的onDestory,手动调用GC,而后经过ReferenceQueue+WeakReference,来判断Activity对象是否被回收,而后结合dump Heap的hpof文件,经过Haha开源库分析泄露的位置android
注册Activity的生命周期的监听器git
经过Application.registerActivityLifecycleCallbacks()
方法注册Activity的生命周期的监听器,每个Actvity的生命周期都会回调到这个ActivityLifecycleCallbacks上,若是一个Activity走到了onDestory,那么就意味着他就再也不存在,而后检测这个Activity是不是真的被销毁github
经过ReferenceQueue+WeakReference,来判断对象是否被回收算法
WeakReference建立时,能够传入一个ReferenceQueue对象,假如WeakReference中引用对象被回收,那么就会把WeakReference对象添加到ReferenceQueue中,能够经过ReferenceQueue中是否为空来判断,被引用对象是否被回收app
详细介绍推荐博客:www.jianshu.com/p/964fbc301…dom
MessageQueue中加入一个IdleHandler来获得主线程空闲回调ide
这个知识点等以后写一篇Handler源码分析的时候在具体分析源码分析
手动调用GC后还调用了System.runFinalization();
,这个是强制调用已失去引用对象的finalize方法post
在可达性算法中,不可达对象,也不是非死不可,这时他们处于“缓刑”阶段,要宣告一个对象真正死亡须要至少俩个标记阶段, 若是发现对象没有引用链,则会进行第一次标记,并进行一次筛选,筛选的条件是此对象是否有必要进行finalize()方法,当对象没有覆盖finalize(),或者finalize()已经调用过,这俩种都视为“没有必要执行”
Apolication中可经过processName判断是不是任务执行进程
经过processName,来判断进程
public static boolean isInServiceProcess(Context context, Class<? extends Service> serviceClass) {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(context.getPackageName(), GET_SERVICES);
} catch (Exception e) {
CanaryLog.d(e, "Could not get package info for %s", context.getPackageName());
return false;
}
String mainProcess = packageInfo.applicationInfo.processName;
ComponentName component = new ComponentName(context, serviceClass);
ServiceInfo serviceInfo;
try {
serviceInfo = packageManager.getServiceInfo(component, 0);
} catch (PackageManager.NameNotFoundException ignored) {
// Service is disabled.
return false;
}
if (serviceInfo.processName.equals(mainProcess)) {
CanaryLog.d("Did not expect service %s to run in main process %s", serviceClass, mainProcess);
// Technically we are in the service process, but we're not in the service dedicated process.
return false;
}
int myPid = android.os.Process.myPid();
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.RunningAppProcessInfo myProcess = null;
List<ActivityManager.RunningAppProcessInfo> runningProcesses =
activityManager.getRunningAppProcesses();
if (runningProcesses != null) {
for (ActivityManager.RunningAppProcessInfo process : runningProcesses) {
if (process.pid == myPid) {
myProcess = process;
break;
}
}
}
if (myProcess == null) {
CanaryLog.d("Could not find running process for %d", myPid);
return false;
}
return myProcess.processName.equals(serviceInfo.processName);
}
复制代码
mRefWatcher = LeakCanary.install(this);
复制代码
这个是SDK向外暴露的方法,咱们以此为入口进行源码的分析
public static RefWatcher install(Application application) {
return refWatcher(application).listenerServiceClass(DisplayLeakService.class)
.excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
.buildAndInstall();
}
public static AndroidRefWatcherBuilder refWatcher(Context context) {
return new AndroidRefWatcherBuilder(context);
}
复制代码
install
方法首先初始化了一个AndroidRefWatcherBuilder
类,而后经过listenerServiceClass
方法设置了DisplayLeakService
,这个类主要用于分析内存泄露的结果信息,而后发送通知给用户
public final class AndroidRefWatcherBuilder extends RefWatcherBuilder<AndroidRefWatcherBuilder> {
/** * Sets a custom {@link AbstractAnalysisResultService} to listen to analysis results. This * overrides any call to {@link #heapDumpListener(HeapDump.Listener)}. */
public AndroidRefWatcherBuilder listenerServiceClass( Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
return heapDumpListener(new ServiceHeapDumpListener(context, listenerServiceClass));
}
...
}
public class RefWatcherBuilder<T extends RefWatcherBuilder<T>> {
...
/** @see HeapDump.Listener */
public final T heapDumpListener(HeapDump.Listener heapDumpListener) {
this.heapDumpListener = heapDumpListener;
return self();
}
...
}
复制代码
而后调用excludedRefs
方法添加白名单,在AndroidExcludedRefs
枚举类中定义了忽略列表信息,若是这些列表中的类发生了内存泄露,并不会显示出来,同时HeapAnalyzer
计算GCRoot强引用路径,也会忽略这些类,若是你但愿本身项目中某个类泄露的,可是不但愿他显示,就能够把类添加到这个上面
public enum AndroidExcludedRefs {
// ######## Android SDK Excluded refs ########
ACTIVITY_CLIENT_RECORD__NEXT_IDLE(SDK_INT >= KITKAT && SDK_INT <= LOLLIPOP) {
@Override void add(ExcludedRefs.Builder excluded) {
excluded.instanceField("android.app.ActivityThread$ActivityClientRecord", "nextIdle")
.reason("Android AOSP sometimes keeps a reference to a destroyed activity as a"
+ " nextIdle client record in the android.app.ActivityThread.mActivities map."
+ " Not sure what's going on there, input welcome.");
}
}
...
}
复制代码
最后调用了buildAndInstall
方法,建立了一个RefWatcher
对象并返回,这个对象是用于检测是否有对象未被回收致使的内存泄露
/** * Creates a {@link RefWatcher} instance and starts watching activity references (on ICS+). */
public RefWatcher buildAndInstall() {
RefWatcher refWatcher = build();
if (refWatcher != DISABLED) {
LeakCanary.enableDisplayLeakActivity(context);
ActivityRefWatcher.install((Application) context, refWatcher);
}
return refWatcher;
}
复制代码
由于分析泄露是在另外一个进程进行的,因此判断当前启动的Application是否在分析内存泄露的进程中,若是是就直接返回DISABLED
,不在进行后续初始化,若是发现是在程序主进程中,就进行初始化
LeakCanary.enableDisplayLeakActivity(context);
主要做用是调用PackageManager
将DisplayLeakActivity
设置为可用。
public static void enableDisplayLeakActivity(Context context) {
setEnabled(context, DisplayLeakActivity.class, true);
}
public static void setEnabled(Context context, final Class<?> componentClass, final boolean enabled) {
final Context appContext = context.getApplicationContext();
executeOnFileIoThread(new Runnable() {
@Override public void run() {
setEnabledBlocking(appContext, componentClass, enabled);
}
});
}
public static void setEnabledBlocking(Context appContext, Class<?> componentClass, boolean enabled) {
ComponentName component = new ComponentName(appContext, componentClass);
PackageManager packageManager = appContext.getPackageManager();
int newState = enabled ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
// Blocks on IPC.
packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP);
}
复制代码
从配置文件看LeakCanary这几个文件都是运行在新进程的,DisplayLeakActivity
默认enable=false
,这样就能够一开始隐藏启动图标
<application>
<service
android:name=".internal.HeapAnalyzerService"
android:process=":leakcanary"
android:enabled="false"/>
<service
android:name=".DisplayLeakService"
android:process=":leakcanary"
android:enabled="false"/>
<activity
android:theme="@style/leak_canary_LeakCanary.Base"
android:name=".internal.DisplayLeakActivity"
android:process=":leakcanary"
android:enabled="false"
android:label="@string/leak_canary_display_activity_label"
android:icon="@drawable/leak_canary_icon"
android:taskAffinity="com.squareup.leakcanary.${applicationId}">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:theme="@style/leak_canary_Theme.Transparent"
android:name=".internal.RequestStoragePermissionActivity"
android:process=":leakcanary"
android:taskAffinity="com.squareup.leakcanary.${applicationId}"
android:enabled="false"
android:excludeFromRecents="true"
android:icon="@drawable/leak_canary_icon"
android:label="@string/leak_canary_storage_permission_activity_label"/>
</application>
复制代码
接着 ActivityRefWatcher.install((Application) context, refWatcher);
这里把refWatcher
当作参数传入,同时对Activity的生命周期进行了监听
public static void install(Application application, RefWatcher refWatcher) {
new ActivityRefWatcher(application, refWatcher).watchActivities();
}
public void watchActivities() {
// Make sure you don't get installed twice.
stopWatchingActivities();
application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
}
public void stopWatchingActivities() {
application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
}
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
new Application.ActivityLifecycleCallbacks() {
@Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override public void onActivityStarted(Activity activity) {
}
@Override public void onActivityResumed(Activity activity) {
}
@Override public void onActivityPaused(Activity activity) {
}
@Override public void onActivityStopped(Activity activity) {
}
@Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override public void onActivityDestroyed(Activity activity) {
ActivityRefWatcher.this.onActivityDestroyed(activity);
}
};
void onActivityDestroyed(Activity activity) {
refWatcher.watch(activity);
}
复制代码
首先就是注册Activity的生命周期的监听器lifecycleCallbacks
,这个监听器能够监听项目中全部Activity的的生命周期,而后在Activity销毁调用onActivityDestroyed
的时候,LeakCanary就会获取这个Activity,而后对其进行分析,看是否有内存泄露
这里分析对象是否内存泄露的是RefWatcher
类,下面简单介绍一下这个类的成员变量
Runtime.getRuntime().gc()
,手动触发GC从上面能够看出,每当Activity销毁,就会调用RefWatcher
的watch
方法,去分析是不是内存泄露
public void watch(Object watchedReference) {
watch(watchedReference, "");
}
public void watch(Object watchedReference, String referenceName) {
if (this == DISABLED) {
return;
}
checkNotNull(watchedReference, "watchedReference");
checkNotNull(referenceName, "referenceName");
final long watchStartNanoTime = System.nanoTime();
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyedWeakReference reference =
new KeyedWeakReference(watchedReference, key, referenceName, queue);
ensureGoneAsync(watchStartNanoTime, reference);
}
复制代码
上面代码主要做用是,先生成一个随机数key放在retainedKeys
容器里,用来区分对象是否被回收,建立了一个弱引用,而后把要分析的Activity对象存入,而后调用了ensureGoneAsync
方法
private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {
watchExecutor.execute(new Retryable() {
@Override public Retryable.Result run() {
return ensureGone(reference, watchStartNanoTime);
}
});
}
复制代码
而后用watchExecutor
去调度分析任务,这个主要是保证,在主线程进行,延迟5s,让系统有时间GC
@SuppressWarnings("ReferenceEquality") // Explicitly checking for named null.
Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
removeWeaklyReachableReferences();
if (debuggerControl.isDebuggerAttached()) {
// The debugger can create false leaks.
return RETRY;
}
if (gone(reference)) {
return DONE;
}
gcTrigger.runGc();
removeWeaklyReachableReferences();
if (!gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
File heapDumpFile = heapDumper.dumpHeap();
if (heapDumpFile == RETRY_LATER) {
// Could not dump the heap.
return RETRY;
}
long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
heapdumpListener.analyze(
new HeapDump(heapDumpFile, reference.key, reference.name, excludedRefs, watchDurationMs,
gcDurationMs, heapDumpDurationMs));
}
return DONE;
}
private void removeWeaklyReachableReferences() {
// WeakReferences are enqueued as soon as the object to which they point to becomes weakly
// reachable. This is before finalization or garbage collection has actually happened.
KeyedWeakReference ref;
while ((ref = (KeyedWeakReference) queue.poll()) != null) {
retainedKeys.remove(ref.key);
}
}
private boolean gone(KeyedWeakReference reference) {
return !retainedKeys.contains(reference.key);
}
复制代码
首先经过removeWeaklyReachableReferences()
方法,尝试从弱引用队列获取待分析对象,若是不为空说明被系统回收了,就把retainedKeys
中的key值移除,若是被系统回收直接返回DONE,若是没有被系统回收,就手动调用 gcTrigger.runGc();
手动触发系统gc,而后再次调用removeWeaklyReachableReferences()
方法,如过仍是为空,则判断为内存泄露
GcTrigger DEFAULT = new GcTrigger() {
@Override public void runGc() {
// Code taken from AOSP FinalizationTest:
// https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
// java/lang/ref/FinalizationTester.java
// System.gc() does not garbage collect every time. Runtime.gc() is
// more likely to perfom a gc.
Runtime.getRuntime().gc();
enqueueReferences();
System.runFinalization();
}
private void enqueueReferences() {
// Hack. We don't have a programmatic way to wait for the reference queue daemon to move
// references to the appropriate queues.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
};
复制代码
手动触发GC后,调用enqueueReferences
方法沉睡100ms,给系统GC时间, System.runFinalization();
,这个是强制调用已失去引用对象的finalize方法
肯定有内存泄漏后,调用heapDumper.dumpHeap();
生成.hprof
文件,而后回调到heapdumpListener
监听,这个监听实现是ServiceHeapDumpListener
类,会调analyze()
方法
public final class ServiceHeapDumpListener implements HeapDump.Listener {
...
@Override public void analyze(HeapDump heapDump) {
checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
}
}
复制代码
HeapDump
是一个modle类,里面用于储存一些分析类强引用的须要信息 HeapAnalyzerService.runAnalysis
方法是发送了一个intent,启动了HeapAnalyzerService服务,这是一个intentService
public static void runAnalysis(Context context, HeapDump heapDump, Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
Intent intent = new Intent(context, HeapAnalyzerService.class);
intent.putExtra(LISTENER_CLASS_EXTRA, listenerServiceClass.getName());
intent.putExtra(HEAPDUMP_EXTRA, heapDump);
context.startService(intent);
}
复制代码
启动服务后,会在onHandleIntent
方法启动分析,找到内存泄露的引用关系
@Override
protected void onHandleIntent(Intent intent) {
if (intent == null) {
CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.");
return;
}
String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);
HeapAnalyzer heapAnalyzer = new HeapAnalyzer(heapDump.excludedRefs);
AnalysisResult result = heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey);
AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
}
复制代码
HeapAnalyzer
对象,而后调用checkForLeak
方法来分析最终获得的结果,checkForLeak
这里用到了Square的另外一个库haha,哈哈哈哈哈,名字真的就是叫这个,开源地址:github.com/square/haha…AbstractAnalysisResultService.sendResultToListener()
方法,这个方法启动了另外一个服务public static void sendResultToListener(Context context, String listenerServiceClassName, HeapDump heapDump, AnalysisResult result) {
Class<?> listenerServiceClass;
try {
listenerServiceClass = Class.forName(listenerServiceClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
Intent intent = new Intent(context, listenerServiceClass);
intent.putExtra(HEAP_DUMP_EXTRA, heapDump);
intent.putExtra(RESULT_EXTRA, result);
context.startService(intent);
}
复制代码
listenerServiceClassName
就是开始LeakCanary.install
方法传入的DisplayLeakService
,它自己也是一个intentService
@Override
protected final void onHandleIntent(Intent intent) {
HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAP_DUMP_EXTRA);
AnalysisResult result = (AnalysisResult) intent.getSerializableExtra(RESULT_EXTRA);
try {
onHeapAnalyzed(heapDump, result);
} finally {
//noinspection ResultOfMethodCallIgnored
heapDump.heapDumpFile.delete();
}
}
复制代码
而后调用自身的onHeapAnalyzed
方法
protected final void onHeapAnalyzed(HeapDump heapDump, AnalysisResult result) {
String leakInfo = LeakCanary.leakInfo(this, heapDump, result, true);
CanaryLog.d("%s", new Object[]{leakInfo});
boolean resultSaved = false;
boolean shouldSaveResult = result.leakFound || result.failure != null;
if(shouldSaveResult) {
heapDump = this.renameHeapdump(heapDump);
resultSaved = this.saveResult(heapDump, result);
}
PendingIntent pendingIntent;
String contentTitle;
String contentText;
// 设置消息通知的 pendingIntent/contentTitle/contentText
...
int notificationId1 = (int)(SystemClock.uptimeMillis() / 1000L);
LeakCanaryInternals.showNotification(this, contentTitle, contentText, pendingIntent, notificationId1);
this.afterDefaultHandling(heapDump, result, leakInfo);
}
复制代码
这个方法首先判断是否须要把信息存到本地,若是须要就存到本地,而后设置消息通知的基本信息,最后经过LeakCanaryInternals.showNotification方法调用系统的系统通知栏,告诉用户有内存泄露
至此LeakCanary的检测内存泄露源码,已经分析完了