由于Worker
类是由框架(WorkerManager
)创建的,我们如何将 @Inject 字段用于Worker
?
答案 0 :(得分:9)
您必须在模块中使用@Provides
注释来提供类。
首先创建一个包含将提供该类的模块的组件。
@Component(modules = {Module.class})
public interface Component1{
void inject(SyncWorker syncWorker);
}
模块类
@Module
public class Module{
@Provides
public ISettingRepository getSettingRepo(){
return new ISettingRepository();
}
}
现在在您的代码中编写一个构造函数,该构造函数用于将组件注入到您的worker类中。
public class SyncWorker extends Worker {
@Inject
ISettingRepository settingRepository;
public SyncWorker(){
DaggerComponent1.builder().build().inject();
}
@NonNull
@Override
public Result doWork() {
sync();
return Result.SUCCESS;
}
private void sync() {
}
}
答案 1 :(得分:2)
我正在使用these系列帖子来在我的应用和ProfileManager
中实现匕首
是我在inject
类中对Worker
拥有的类。
UploadWorker
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();
}
}
在 Application 类中,我在Appcomponent
类中设置Provider
@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();
}
}