You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Hilt注入@ApplicationContext至Service调用类的疑问咨询

Hilt依赖注入相关问题解答

问题1:@ApplicationContext注入的是否为UIApp实例?

是的,你的判断正确。在Hilt中,@ApplicationContext注解注入的Context对象,就是你自定义的Application子类UIApp的实例。Hilt会自动将Application实例作为全局ApplicationContext提供,这个Context的生命周期和整个应用进程一致,是安全的,不会因页面或组件的销毁而失效。

问题2:应用销毁但ServiceTranslate仍在后台运行时,应用会崩溃吗?

首先明确:Service依附于应用进程存在,如果应用进程被系统销毁,运行在该进程中的Service也会同步终止,不存在“应用销毁但Service还在后台运行”的情况。

结合你的代码场景具体说明:

  • TranslateIncompleted中使用的是Application级别的Context,只要进程存活,这个Context就始终有效,调用getString()这类方法不会出现问题。
  • 如果ServiceTranslate是普通后台服务,系统资源紧张时进程可能被回收,此时Service会被终止,但不会因Context问题导致崩溃;如果是前台服务,系统会优先保留进程,Service可持续运行,ApplicationContext也能正常使用。
  • 你的Service是绑定服务(通过onBind返回Binder),当所有绑定的客户端都解绑后,Service会被系统销毁,同样不会出现Context相关的崩溃问题。

附代码示例

class TranslateIncompleted @Inject constructor(
   @ApplicationContext private val appContext: Context       //我担心这可能会引发问题。
): ITranslateIncompleted {

    override suspend fun translateIncompletedAndUpdate() {
        val myString = appContext.getString(R.string.translate_incompleted)        
    }
}


@AndroidEntryPoint
class ServiceTranslate: Service() {

    @Inject lateinit var translateIncompleted: ITranslateIncompleted 
 
    inner class MyBinder : Binder() {
        val serviceTranslate: ServiceTranslate
            get() = this@ServiceTranslate
    }

    override fun onBind(intent: Intent): IBinder {
        return MyBinder()
    } 
}


@HiltAndroidApp
class UIApp : Application() {

}

内容的提问来源于stack exchange,提问作者HelloCW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:33:18