Skip to content Skip to sidebar Skip to footer

Workmanager Java Android Dagger2

I NEED working Workmanager in Android app with JAVA only (without Kotlin!!!). In a project, we use just dagger2.8 (without android-dagger!) and I need to inject or access to some I

Solution 1:

As described in the article you linked, you need to use a WorkManager's custom configuration with a custom WorkerFactory that pass an additional parameter to your Worker class:

publicclassUIUpdaterWorkerextendsWorker {
    privateStringTAG= getClass().getSimpleName();

    publicUIUpdaterWorker(
            @NonNull Context context,
            @NonNull WorkerParameters workerParams,
            @NonNull DBModel dbModel
    ) {
        super(context, workerParams);
    }

    @NonNull@Overridepublic Result doWork() {
        Log.d(TAG, dbModel.toString());
        return Result.success();
    }
}

You can then injected this with Dagger (DBModel in your case).

I like the new `DelegatingWorkerFactory' functionality added in WorkManager 2.1.0-alpha02 (or you can roll your own take on a similar design). I made a PoC (in Kotlin) that create a custom configuration and register a WorkerFactory for a specific worker that needs an additional parameter injected with dagger.

You can find the code on this Plaid branch, Worker and WorkerFactory are here. To provide more guidance on your specific case it would be helpful to have some more context. I can imagine that you are already injecting the dbModel in other classes.

You can do the same when you register your custom WorkerFactory, injecting the dbModel, so that you can then pass that as a parameter to the Worker class.

Post a Comment for "Workmanager Java Android Dagger2"