如何在应用程序中访问 Hilt 模块 class

How to access Hilt module in Application class

我有申请classMainApplication

我需要访问此 class 中的 Hilt 模块:

我怎样才能做到这一点?

我看到你想将 HCERepository 注入 Activity。尝试以下操作:

@AndroidEntryPoint
class YourActivity : AppCompatActivity() {

    @Inject
    lateinit var hceRepository: HceRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        // Try to call anything of hceRepository in here.
    }
}

因为您注入了模块 ApplicationComponent(较新的 Hilt 版本将为 SingletonComponent),您可以将 HceRepository 注入 Activity.

在此处了解更多信息:Dependency injection with Hilt

@HiltAndroidApp
class MainApplication : MultiDexApplication() {

    @Inject
    lateinit var hceRepository: HceRepository //new

    override fun onCreate() {
        // Try to call anything of hceRepository in here.
    }
}

在应用程序中执行字段注入class。这应该够了