既然Worker
类是由框架(WorkerManager
(创建的,我们如何在Worker
中使用@Inject字段?
我正在使用这一系列帖子在我的应用程序和ProfileManager
中实现dagger 是我想在Worker
课上inject
的班级。
上传工作者
public class UploadWorker extends Worker {
@Inject
ProfileManager profileManager;
@Inject
@SuppressWarnings("WeakerAccess")
public UploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
Provider.getAppComponent().inject(this);
}
@NonNull
@Override
public Result doWork() {
profileManager.someMethod();
}
}
在应用程序类中,我在Provider
类中设置Appcomponent
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
AppComponent appComponent = DaggerAppComponent.builder().application(this).build();
appComponent.inject(this);
Provider.setAppComponent(appComponent);
return appComponent;
}
供应商
public class Provider {
private static AppComponent appComponent;
public static AppComponent getAppComponent() {
return appComponent;
}
public static void setAppComponent(AppComponent component) {
appComponent = component;
}
}
应用组件
@Singleton
@Component(modules = {
AndroidSupportInjectionModule.class,
ActivityBuilderModule.class,
ApiModule.class,
AppModule.class,
ViewModelModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
@Override
void inject(DaggerApplication instance);
void inject(MyApplication app);
void inject(UploadWorker uploadWorker);
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}