I have a Worker which Injects 2 classes, UriUtil and CameraUtil. Both classes are being provided by the AppModule. Even in other classes which do have inheritance with for example FileProvider, or don't inherit any class at all. The vars remain null which, if I'm correct, should be provided by the field injection.
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun uriUtil(): UriUtil { return UriUtil() }
@Provides
@Singleton
fun cameraUtil(): CameraUtil { return CameraUtil() }
}
My worker then tries to field inject, but they remain null:
@HiltWorker
class SendToBackendWorker @AssistedInject constructor(
@Assisted val context: Context,
@Assisted val workerParams: WorkerParameters
) : Worker(context, workerParams) {
...
@Inject
lateinit var uriUtil: UriUtil
@Inject
lateinit var cameraUtil: CameraUtil
...
}
As the HiltWorker documentation explained (can be found here), I've updated my Application class:
@HiltAndroidApp
class MyApp : Application(), Configuration.Provider {
@Inject
lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
}
My AndroidManifest contains:
<application
android:name=".MyApp"
...
Can I perhaps only use field injection in classes which inherit from the ones mentioned here?
CodePudding user response:
I've found the solution. There's some additional code required for 'custom' classes, which do not inherit from the ones mentioned here.
For example, to fix the @Inject code in my Worker I had to add an @EntryPoint notation and provide it an interface:
@InstallIn(SingletonComponent::class)
@EntryPoint
interface BackendWorkerEntryPoint {
fun uriUtil(): UriUtil
fun cameraUtil(): CameraUtil
}
private fun hiltEntryPoint(appContext: Context) = EntryPointAccessors.fromApplication(
appContext,
BackendWorkerEntryPoint::class.java
)
private fun getCameraUtil(appContext: Context): CameraUtil =
hiltEntryPoint(appContext).cameraUtil()
private var cameraUtil = getCameraUtil(context)
...
CodePudding user response:
For workManager library version 2.6.0-alpha01 and above you must add this code to your manifest:
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="remove" />
read warning in the bottom of this page from developers.android.com
