gpt4 book ai didi

android - Activity的onDestroy()方法中是否需要设置variable = null?

转载 作者:搜寻专家 更新时间:2023-11-01 07:48:20 24 4
gpt4 key购买 nike

在我公司的 android 项目(10k+ 用户)中,我们几乎在每个 Activity 的 onDestory() 方法中都设置了 variable = null。代码如下:

@Override
protected void onDestroy() {
LogUtil.i(TAG, "onDestroy");
//mImageView = null;
if(pagerAdapter != null){
pagerAdapter.clear();
pagerAdapter = null;
}
if(mediaList != null){
mediaList.clear();
mediaList = null;
}
viewPager = null;
clickedMsg = null;
instance = null;
msg = null;
//System.gc();
super.onDestroy();
}

有必要吗?谢谢你回答我的问题~

最佳答案

在你的情况下它没有必要。并注意:

There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

来自docs .

那么什么时候应该在onDestroy()中取消?

当有引用保存 Activity 时,不会被垃圾收集。例如,一个静态变量在其参数或方法中保存一个 Activity 。此外,一些 Singleton 设计模式使用执行不佳的代码来执行此操作,因此请小心并通过 onDestroy() 释放它。

关于android - Activity的onDestroy()方法中是否需要设置variable = null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39218264/

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