.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
,这样就可以一开始隐藏启动图标
接着 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.registerActivityLifec