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

标签 android

在我公司的 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 。另外,一些单例设计模式使用执行不佳的代码来实现此目的,因此请小心并通过 onDestroy() 释放它。

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

相关文章:

java - Fragment 中的 RecyclerView – 如何从数组列表中检索数据

android - Android模拟器没有声音

java - FragmentTransaction 仅在纵向模式下工作

android - 某些设备上的 ANR 内部功能

java - 是否可以在 Android 中运行时执行 Java 代码字符串?

android - 来自 pdf android 的大拇指

java - 如何在没有初始动画的情况下更新 ListView 内的 SpeedView?

安卓反破解,到底值不值?

android - 防止 Android Webview 更改字体大小(计算样式)

android - textview在android中切断一个字母