Android WorkManager Worker can not be injected using Dagger Hilt `@WorkerInject`
Asked Answered
S

3

24

I am trying to follow guide from https://developer.android.com/training/dependency-injection/hilt-jetpack#workmanager and encountered following error

E/WM-WorkerFactory: Could not instantiate com.example.android.hilt.ExampleWorker
    java.lang.NoSuchMethodException: <init> [class android.content.Context, class androidx.work.WorkerParameters]

To reproduce the issue, I have added the example code from the gude in the Dagger Hilt Example Repo

class ExampleWorker @WorkerInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    val workerDependency: AppNavigator
) : Worker(appContext, workerParams) {
    override fun doWork(): Result {
        Log.d("WORKER", "I am the worker, got dependency: $workerDependency")
        return Result.success()
    }
}

NOTE: The AppNavigator is provided in NavigationModule as @Binds abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator.
Also note, replacing AppNavigator with AppDatabase which is @Singleton does not help.

And this is how I start the worker from MainActivity

    override fun onStart() {
        super.onStart()
        enqueueWorker(applicationContext)
    }

    private fun enqueueWorker(context: Context) {
        val request = OneTimeWorkRequestBuilder<ExampleWorker>().build()
        WorkManager.getInstance(context).enqueue(request)
    }

Not sure what exactly is wrong.


UPDATE: I have created a brand new Android project to reproduce it. The project is attached to the issue#158843197. All the key file source code snapshot is available at GitHub Gist (if you want to do a quick review).


UPDATE#2: The solution

On top of what Ian mentioned below, the issue was I missed following Gradle dependency in app/build.gradle (mentioned in aosp#158843197)

kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'

The dependency injection for Worker is now working.

Stoss answered 13/6, 2020 at 3:46 Comment(1)
Reported this issue at the issue tracker issuetracker.google.com/issues/158843197Stoss
K
23

Update (March 24, 2021):

Since androidx.work-* version 2.6.0-alpha01, WorkManager uses androidx.startup to initialize WorkManager.
For the new required changes to AndroidManifest.xml, check this answer.

Original Answer:

As per the WorkManager Configuration and Initialization documentation, to use the Configuration.Provider interface on your Application, you must remove the default initializer:

<!-- In your AndroidManifest.xml -->
<provider
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:authorities="${applicationId}.workmanager-init"
    tools:node="remove" />

Otherwise, the default initializer will still run, wiping out your custom intialization and its HiltWorkerFactory.

Konikow answered 13/6, 2020 at 4:11 Comment(8)
Thanks Ian, I wasn't aware of this. I have applied the rule in Manifest, and validated the record is removed from merged Manifest by using "Analyze APK". However, I am still getting same error. Sorry, I may be missing something silly I can't see.Stoss
I was facing the same issue and this answer solve it, thanks. Maybe it would be helpful if this snnipet (or some indication) had been included in the Hilt+WorkManager guide?Otology
@Otology thanks for the update here. Strangely it's still not working for me. As a workaround, the solution mentioned in Inject dependencies in classes not supported by Hilt worked for me. However, I would prefer to use Hilt's provided @WorkerInject solution.Stoss
I debugged source, looks like when HiltWorkerFactory.createWorker() is invoked, the HiltWorkerFactory.mWorkerFactories: Map<String, Provider> has 0 items. Hence it's likely failing with the error mentioned above. I will start with brand new project to reproduce this issue. It's likely I am doing something wrong.Stoss
@Otology - I'd strongly encourage you to file an issue against the documentation so that a link can be added.Konikow
I filed the documentation confusion issue at issuetracker.google.com/issues/158891026Stoss
Got response from AOSP issue, I was missing kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01' in my app/build.gradle 🤦‍♂️. Working now! 😃Stoss
nothing changed - #73634784Expropriate
I
0

I had a similar issue but in my case, I had to use Hilt modules with @Provides annotation instead of @Binds annotation. I couldn't inject Hilt modules with @Binds annotation.

Iambus answered 12/1, 2021 at 9:53 Comment(0)
S
0

In my case, I was missing a dependency. I was missing this: ksp("androidx.hilt:hilt-compiler:1.2.0") or if using kapt kapt("androidx.hilt:hilt-compiler:1.2.0"). I added that and error went away.

Shively answered 19/4, 2024 at 3:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.