如何使用Android Studio中的ViewModel()使用HILT依赖性注入上下文?

发布于 2025-01-23 17:53:04 字数 793 浏览 0 评论 0原文

我希望能与Hilt for ViewModel进行依赖注入上下文,

我已经阅读了文章 ,并基于代码A的文章。

但是我得到以下警告信息,为什么?我该如何修复?

此字段泄漏了一个上下文对象

btw,我读过 atrate ,我的项目是hilt_version ='2.41'

代码a

@HiltViewModel
class SoundViewModel @Inject constructor(
    @ApplicationContext private val mContext: Context,  //It cause  a warning information
    private val aSoundMeter: ISoundMeter  
): ViewModel() {


}

I hope to dependency injection Context with Hilt for ViewModel,

I have read the article, and Code A based the article.

But I get the following warning information, why? How can I fix it?

This field leaks a context object

BTW, I have read the article, and my project is hilt_version = '2.41' .

Code A

@HiltViewModel
class SoundViewModel @Inject constructor(
    @ApplicationContext private val mContext: Context,  //It cause  a warning information
    private val aSoundMeter: ISoundMeter  
): ViewModel() {


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虚拟世界 2025-01-30 17:53:04

使用AndroidViewModel而不是ViewModel

class SoundViewModel @Inject constructor(
    @ApplicationContext private val mContext: Application,
    private val aSoundMeter: ISoundMeter  
): AndroidViewModel(mContext)

Use AndroidViewModel instead of ViewModel

class SoundViewModel @Inject constructor(
    @ApplicationContext private val mContext: Application,
    private val aSoundMeter: ISoundMeter  
): AndroidViewModel(mContext)
美男兮 2025-01-30 17:53:04

您必须遵循官方指南首先。

@HiltViewModel
class ExampleViewModel @Inject constructor(
  private val application: Application,
) : ViewModel() {
  ...
}

或者

@HiltViewModel
class ExampleViewModel @Inject constructor(
  @ApplicationContext private val mContext: Context,
) : ViewModel() {
  ...
}

You must follow the latest version of the official guide first.

@HiltViewModel
class ExampleViewModel @Inject constructor(
  private val application: Application,
) : ViewModel() {
  ...
}

or

@HiltViewModel
class ExampleViewModel @Inject constructor(
  @ApplicationContext private val mContext: Context,
) : ViewModel() {
  ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文