我有一个关于将多个片段注入(inject) Activity 字段的问题。目前,我已经进行了这样的设置(所有片段都扩展了DaggerFragment并且 Activity 是DaggerAppCompatActivity):

@Inject
lateinit var fragmentOne: FragmentOne
@Inject
lateinit var fragmentTwo: FragmentTwo
@Inject
lateinit var fragmentThree: FragmentThree

override fun onCreate(...) {
    ...
    startFirstFragment()
}

fun startFirstFragment() {
    supportFragmentManager.beginTransaction()
            .replace(containerId, fragmentOne).commit()
}

fun startSecondFragment() {
    supportFragmentManager.beginTransaction()
            .replace(containerId, fragmentTwo).commit()
}

一切正常,直到我添加LeakCanary,它说,当我用第二个替换第一个片段时,被替换的实例通过lateinit var fragmentOne泄漏,因为它保留了对第一个片段的引用。我的问题是:什么时候 Dagger 会清空字段,它是正确执行的,并且应该归咎于谁: Dagger 会导致泄漏,LeakCanary会导致误报泄漏检测或其他?

ApplicationComponent:
@ApplicationScoped
@Component(
        modules = [
            AndroidSupportInjectionModule::class,
            ActivityBindingModule::class,
            ApplicationModule::class,
            RepositoriesModule::class,
            NetworkModule::class]
)
interface ApplicationComponent : AndroidInjector<MyApp> {

    override fun inject(instance: MyApp?)

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder
        fun build(): ApplicationComponent
    }
}

ActivityBindingModule:
@Module
abstract class ActivityBindingModule {

    ...

    @ActivityScoped
    @ContributesAndroidInjector(modules = [ActivityInQuestionModule::class])
    internal abstract fun aiqActivity(): ActivityInQuestion

    @ActivityScoped
    @Binds
    internal abstract fun fragmentSwitcher(activityInQuestion: ActivityInquestion): FragmentSwitcher

}

ActivityInQuestionModule:
@Module
abstract class ActivityInQuestionModule {

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentOne(): FragmentOne

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentTwo(): FragmentTwo

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentThree(): FragmentThree

}

最佳答案

我很确定 Dagger 不是泄漏的原因(如果存在的话)。 Dagger 所做的只是用适当的实例实例化 Activity 的成员。因此,您可以尝试使用修改如下的代码来运行LeakCarnary:lateinit var fragmentOne = FragmentOne() ...并验证是否存在内存泄漏。也许问题出在您的片段代码中。

08-28 14:43