gpt4 book ai didi

android - 空 Activity 中的内存泄漏

转载 作者:太空狗 更新时间:2023-10-29 13:12:28 30 4
gpt4 key购买 nike

我最近决定在我的项目中使用 leakcanary,所以我创建了一个带有空 Activity 的项目,只是为了测试,当我运行应用程序时(在项目创建之后,没有逻辑代码或 View )我从这个库中得到了内存泄漏日志:

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);
}
}

我不知道为什么会这样,如果有人向我解释一下,我将不胜感激。

最佳答案

您的RefWatcher 应该在onDestroy() 方法中,而不是onCreate()(参见类似的reported issue here)。

您甚至不需要这样做,因为 LeakCanary 会自动监视 Activity 引用。来自FAQ :

LeakCanary.install() returns a pre configured RefWatcher. It also installs an ActivityRefWatcher that automatically detects if an activity is leaking after Activity.onDestroy() has been called.

关于android - 空 Activity 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470388/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com