问题描述
我最近决定在我的项目中使用 leakcanary,所以我创建了一个带有空 Activity
仅用于测试,当我运行应用程序时(在没有逻辑代码或视图的项目创建之后)我从这个库中得到了内存泄漏日志:
I recently decided to use leakcanary in my projects, So I created a project with an empty Activity
just for test, When I run the app (just after project creation with no logic code or views) I got memory leak log from this library:
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * com.example.leaktest.MainActivity has leaked:
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * GC ROOT static android.app.ActivityThread.sCurrentActivityThread
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * references android.app.ActivityThread.mActivities
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * references android.util.ArrayMap.mArray
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * references array java.lang.Object[].[1]
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * references android.app.ActivityThread$ActivityClientRecord.activity
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * leaks com.example.leaktest.MainActivity instance
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * Retaining: 1.7KB.
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * Reference Key: 9180226a-8a65-4c94-9d12-4562a6d88157
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * Device: Genymotion generic genymotion_vbox86tp_5.1_150409_105318 vbox86tp
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * Android Version: 5.1 API: 22 LeakCanary: 1.4-beta2 3799172
07-20 04:32:36.742 2967-4915/com.example.leaktest D/LeakCanary: * Durations: watch=5808ms, gc=158ms, heap dump=1953ms, analysis=15795ms
应用类:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
App application = (App) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
}
MainActivity 类:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
App.getRefWatcher(this).watch(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
我不知道为什么会这样,如果有人向我解释,我将不胜感激.
I have no idea why this is happening, I will appreciate if someone explain it to me.
推荐答案
你的 RefWatcher
应该在 onDestroy()
方法中,而不是 onCreate()
(请参阅此处报告的问题).
Your RefWatcher
should be in the onDestroy()
method, not onCreate()
(see a similar reported issue here).
您甚至不需要这样做,因为 LeakCanary 会自动监视 Activity
引用.来自 FAQ:
You don't even need to do this, since LeakCanary watches Activity
references automatically. From the FAQ:
LeakCanary.install() 返回一个预配置的 RefWatcher.它还安装了一个 ActivityRefWatcher,它会在 Activity.onDestroy() 被调用后自动检测活动是否泄漏.
这篇关于空活动中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!