Они по-прежнему не имеют внутренней поддержки WorkManager.Скорее всего, это будет новый артефакт (dagger-android-work
), плюс поддержка @ContributesAndroidInjector
.
Но мы можем создать свое собственное все, чтобы это сделать.Следуйте приведенному ниже коду.
AppComponent.java
@Singleton
@Component(modules = {//rest of your modules,
AndroidWorkerInjectionModule.class,
WorkerModule.class})
public interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
void inject(App npp);
DataManager getDataManager();
}
AndroidWorkerInjectionModule.java
@Module
public abstract class AndroidWorkerInjectionModule {
@Multibinds
abstract Map<Class<? extends Worker>, AndroidInjector.Factory<? extends
Worker>>
workerInjectorFactories();
}
WorkerModule.class
@Module(subcomponents = {
WorkerComponent.class
})
public abstract class WorkerModule {
@Binds
@IntoMap
@WorkerKey(CustomWorkManager.class)
abstract AndroidInjector.Factory<? extends Worker>
bindProfileWorkerFactory(WorkerComponent.Builder profileWorker);
}
WorkerComponent.class
@Subcomponent
public interface WorkerComponent extends AndroidInjector<CustomWorkManager> {
//Here, CustomWorkManager is the class that extends Worker of WorkManager.You write your own class
@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<CustomWorkManager>{}
}
HasWorkerInjector.class
public interface HasWorkerInjector {
AndroidInjector<Worker> workerInjector();
}
AndroidWorkerInjection.class
public class AndroidWorkerInjection {
public static void inject(Worker worker) {
//TODO : Check not null
Object application = worker.getApplicationContext();
if (!(application instanceof HasWorkerInjector)) {
throw new RuntimeException(
String.format(
"%s does not implement %s",
application.getClass().getCanonicalName(),
HasWorkerInjector.class.getCanonicalName()));
}
AndroidInjector<Worker> workerInjector =
((HasWorkerInjector) application).workerInjector();
checkNotNull(workerInjector, "%s.workerInjector() returned null",
application.getClass());
workerInjector.inject(worker);
}
}
WorkerKey.class
@MapKey
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WorkerKey {
Class<? extends Worker> value();
}
Теперь вы можете добавить все зависимости в CustomWorkManager.Удачного кодирования!