问题
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 Injected classes like DataBase. (it injected in AppComponent).
Already tried: https://proandroiddev.com/dagger-2-setup-with-workmanager-a-complete-step-by-step-guild-bb9f474bde37 in kotlin and rewrite in Java. - there is doesn't work in a project. (and all close titles on StackOverflow)
And a lot of examples around web copied to each other...(all of them in Kotlin...)
I update all libraries to actual versions, update as from 3.2.1 to 3.4.1 with everything that implies.
Use: AS 3.4.1 | gp:3.4.1 | gv: 5.1.1 libraries: Dagger2, Retrofit2, OkHttp, Gson, ButterKnife, RxJava2, Room, Rabbit, WorkManager. And it is on 28 sdk There is my worker:
private String TAG = getClass().getSimpleName();
DBModel dbModel; // this is injected room model in appComponent
public UIUpdaterWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
Log.d(TAG, dbModel.toString()); // here is null
return Result.success();
I tried it in the same component and separate. And it won't work. Have null or project doesn't build.
回答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:
public class UIUpdaterWorker extends Worker {
private String TAG = getClass().getSimpleName();
public UIUpdaterWorker(
@NonNull Context context,
@NonNull WorkerParameters workerParams,
@NonNull DBModel dbModel
) {
super(context, workerParams);
}
@NonNull
@Override
public 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.
来源:https://stackoverflow.com/questions/56378985/workmanager-java-android-dagger2