Search code examples
androidkotlinworkerdagger-hilt

Hilt Worker not getting initiated. Works fine when I use only default params for worker constructor, when I add third param it fails


Seems Like for some reason its not using my custom worker, Instead initiates default Worker.. Following is the code snippet

@HiltWorker
class RequestsWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
var dbRepository: DBRepository) : Worker(appContext, workerParams) {
//doWorK...
}

Application.class

@HiltAndroidApp
class Application: Application(), Configuration.Provider {

@Inject
lateinit var workerFactory: HiltWorkerFactory

override fun onCreate() {
    super.onCreate()
}

override fun getWorkManagerConfiguration(): Configuration {
    return  Configuration.Builder()
        .setMinimumLoggingLevel(Log.DEBUG)
        .setWorkerFactory(workerFactory)
        .build()
}
}

Start worker from fragment

private fun initWorker() {
    val request = OneTimeWorkRequestBuilder<RequestsWorker>().build()
    WorkManager.getInstance(applicationContext).enqueue(request)
}

I get following error

 java.lang.NoSuchMethodException: com.sala.cbc.backgroundsync.RequestsWorker.<init> [class android.content.Context, class androidx.work.WorkerParameters]
    at java.lang.Class.getConstructor0(Class.java:2321)
    at java.lang.Class.getDeclaredConstructor(Class.java:2167)
    at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:95)
    at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:244)
    at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
    at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)

In manifest I added following in application tag

 <provider
        android:name="androidx.startup.InitializationProvider"
        android:authorities="${applicationId}.androidx-startup"
        tools:node="remove">
    </provider>

Solution

  • Try changing your hilt-android-gradle-plugin version inside your Project level build.gradle file.

    It worked for me by upgrading the version from 2.37 to 2.38.1.

    Now it should look like this,

    classpath "com.google.dagger:hilt-android-gradle-plugin:2.38.1"