Reputation: 2325
The Code A is from https://developer.android.com/codelabs/android-hilt#6
And Code B is from https://developer.android.com/codelabs/android-hilt#7
I find the annotation @ApplicationContext is added before appContext: Context in Code A, and none annotation is added before private val activity: FragmentActivity in Code B, why?
And more can I use Code C instead of Code A?
Code A
@Module
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
...
}
}
Code B
class AppNavigatorImpl @Inject constructor(
private val activity: FragmentActivity
) : AppNavigator {
...
}
Code C
@Module
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(appContext: ApplicationContext): AppDatabase {
...
}
}
Upvotes: 2
Views: 793
Reputation: 93834
Singletons live longer than Activities. Since Activity is a subtype of Context, if you pass it to a singleton that hangs onto the reference (just to use it as a Context), then that Activity has been leaked. The @ApplicationContext
is an indicator that you should only pass the application Context as the parameter for the function. The application Context is constant for the lifetime of the app, so it is leak-proof.
The annotation is a way of documenting that you should not pass Activities as the context, but also Lint can warn you if you accidentally do it.
Code C doesn't make sense because you've made the parameter of type ApplicationContext, which is an annotation class and is not a Context subtype.
Upvotes: 3