如何为工人类实现Dagger?

时间:2018-05-22 07:36:38

标签: android dagger-2 android-jetpack android-workmanager

由于Worker类是由框架(WorkerManager)创建的,我们如何将 @Inject 字段用于Worker

2 个答案:

答案 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();
    }

}