Field injection in @HiltWorker using hilt

Viewed 1600

I need to implement field inject in @HiltWorker but field injection returning null. Here is my worker code.

@HiltWorker
public class BackgroundTasks extends Worker {

@Inject
SessionManager sessionManager;


@AssistedInject
public BackgroundTasks(@Assisted @NonNull Context context, @Assisted @NonNull WorkerParameters params) {
    super(context, params);
}

@NonNull
@Override
public Result doWork() {
    Timber.tag("TAGGGGGGG").i(sessionManager.getJwtModel().getUserName());
    return Result.success();
 }
}

Here is my custom work manager configuration

Configuration myConfig = new Configuration.Builder()
            .setMinimumLoggingLevel(android.util.Log.INFO)
            .build();

WorkManager.initialize(this, myConfig);

Here is my manifest file where I am removing the work manager default configuration

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

I hope, it's enough information for understanding my scenario. If anyone needs, please ask. Thanks

1 Answers

WorkManager should be initialized by Hilt. So you should not do

WorkManager.initialize(this, myConfig);

Instead, your Application class sets up like the following.

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

  @Inject lateinit var workerFactory: HiltWorkerFactory

  override fun getWorkManagerConfiguration() =
      Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .build()
}

As explained here.

Related