Search code examples
androidkotlindagger-hilt

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.

ServiceTranslate is a Service class that has a longer lifecycle than the app itself. The ServiceTranslate will invoke the TranslateIncompleted class to perform tasks in the background.

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?

2: Will the app crash when the app is destroyed but ServiceTranslate continues to run in the background?

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() {

}

Solution

    1. Yes, when using @ApplicationContext with Hilt, you're indeed getting an instance of your application class, UIApp in your case.

    2. The Application context in Android is a singleton and lives for the entire lifecycle of the application. In your case, you are injecting the Application context, and as this lives as long as your entire application, it will not cause a crash even if the Service is running and the app's activity is destroyed. Your ServiceTranslate can continue to run and have valid access to the appContext.