"This field leaks a context object" 警告 Hilt 注入

"This field leaks a context object" warning Hilt Injection

我的问题和这个问题类似,在接受的答案中这个问题已经在2.31.2版本中解决了。但是警告仍然存在,我和我使用的是 2.37 版。其他答案对我来说仍然不清楚(实际上没有确认正在发生的事情)。所以这是我的 ViewModel 代码:

@HiltViewModel
class DetailViewModel @Inject constructor(
    private val context: Context,
    private val repository: VaccineRepository,
) : ViewModel() {

这是提供的功能:

@Singleton
@Provides
fun provideApplicationContext(
    @ApplicationContext appContext: Context
): Context = appContext

它确实有效,但警告困扰着我。那么,这只是错误的警告,我只能抑制它还是真的泄漏了?

因为 ViewModels 是为了在存储 activity 上下文的 activity 娱乐中生存,所以会泄漏你的上下文(由于 activity 的性质很容易破坏).但是在整个应用程序被杀死之前,应用程序上下文在应用程序中是唯一的,因此不会有任何实际泄漏,您可以通过将 @SuppressLint("StaticFieldLeak") 添加到 DetailViewModel class.

检查本应考虑您的 @ApplicationContext 注释并得出有意义的结果,但它没有。