[英]Can I use “@ApplicationContext private val appContext: Context” as DI for a class that will be invoked by a Service() in Android Studio?
I am using Hilt as DI in my Android Studio project.我在我的 Android Studio 项目中使用 Hilt 作为 DI。
ServiceTranslate
is a Service
class that has a longer lifecycle than the app itself. ServiceTranslate
是一个Service
class,它的生命周期比应用本身更长。 The ServiceTranslate
will invoke the TranslateIncompleted
class to perform tasks in the background. ServiceTranslate
将调用TranslateIncompleted
class 在后台执行任务。
1: Currently, I am using @ApplicationContext private val appContext: Context
in the TranslateIncompleted
class. I believe appContext
is an instance of the UIApp
class, is that correct? 1:目前,我在
TranslateIncompleted
class 中使用@ApplicationContext private val appContext: Context
我相信appContext
是UIApp
class 的一个实例,对吗?
2: Will the app crash when the app is destroyed but ServiceTranslate
continues to run in the background? 2:应用被销毁但
ServiceTranslate
继续在后台运行时,应用会不会崩溃?
class TranslateIncompleted @Inject constructor(
@ApplicationContext private val appContext: Context //I'm afriad that it maybe cause trouble.
): 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() {
}
ServiceTranslate is a Service class that has a longer lifecycle than the app itself
ServiceTranslate 是一个服务 class ,它的生命周期比应用本身更长
I don't think this statement is correct.我认为这种说法是不正确的。 An instance of Application should always exist if the process is running, which would be the case if the Service is active.
如果进程正在运行,应用程序的实例应该始终存在,如果服务处于活动状态,情况就是如此。 Unless you are running your Service in it's own process, using AppContext should be entirely safe, as Service will always have an associated Application.
除非您在自己的进程中运行您的服务,否则使用 AppContext 应该是完全安全的,因为服务将始终具有关联的应用程序。 You can validate this by putting a log statement in onDestroy of Application, and confirm that it's not called when the app get's backgrounded in the UI while the Service is still active.
您可以通过在应用程序的 onDestroy 中放置一条日志语句来验证这一点,并确认当应用程序在 UI 中处于后台且服务仍处于活动状态时不会调用它。 Related thread
相关话题
Alternately, you could sidestep this concern entirely by exposing Service.getResources() on the Service's DI graph.或者,您可以通过在服务的 DI 图上公开 Service.getResources() 来完全回避这个问题。 That way, you wouldn't need to depend on the Application Context.
这样,您就不需要依赖应用程序上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.