android - 如果我不在 Activity onDestroy() 中将 Dagger 2 Component 设置为 null 会怎样?

标签 android android-activity activity-lifecycle dagger-2

我看到如果有人在 Activity 中实例化 Dagger 2 组件,那么它稍后会在 onDestroy() 方法中为空,如 here 所示.

public class MyActivity {
    private MyActivityComponent component;
    //...

    public void onCreate() {
        component = Dagger_MyActivityComponent.builder()
            .myApplicationComponent(App.getComponent())
            .build()
            .inject(this);

        //...
    }

    public void onDestroy() {
        component = null;
    }
}

如果我不null那个实例会发生什么,会发生什么?

旁注:in comments我发现了有用的提示,为什么有人会将其设置为 null,这非常有说服力:“我认为这不是必需的,但它定义的范围非常清楚”。

最佳答案

What happens if I don't null that instance [...]?

Nothing. onDestroy 被调用后, Activity 对象将在某个时候被垃圾回收。如果 Activity 被重新创建,它将是一个新对象。你的 Dagger 组件也将随你的 Activity 一起被垃圾收集。我通常不会在 onDestroynull 我的组件,因为我认为它没有必要。

如果您保持对您的 Activity 的静态引用或有其他类型的内存和 Activity 泄漏,这虽然不成立。但是,如果您拥有这些,那么即使您null 您的组件也不会有太大的不同。

关于android - 如果我不在 Activity onDestroy() 中将 Dagger 2 Component 设置为 null 会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36915413/

相关文章:

java - 使用 C++ 或 Java 在 IOS 和 Android 移动应用程序上共享代码

android - 移动设备架构 - iOS、Android、WP7 和断开连接的实例

android - 切换到 webview 时的白色背景

Android:无法从服务启动管理状态授予 Activity

android-webview - Android WebView/CookieSyncManager中 session cookie的生命周期

android - 将 Android 库发布到 jCenter

Android Espresso 测试永远不会完成

android - android Activity 生命周期函数的基础知识

android - 尽管已在 manifest.xml 中声明,但未找到 Launcher Activity

android - 每次 Activity 重新加载