如何为 worker 类 实现 Dagger?

How to implement Dagger for worker classes?

由于Worker class是由框架创建的(WorkerManager),我们如何使用@Inject字段到Worker?

您必须在要注入的模块中使用 @Provides 注释提供 class。

首先创建一个包含模块的组件,该模块将提供 class。

@Component(modules = {Module.class})
public interface Component1{

    void inject(SyncWorker syncWorker);
}

模块Class

@Module
public class Module{

    @Provides
    public ISettingRepository getSettingRepo(){
        return new ISettingRepository();
    }

}

现在在您的代码中编写一个构造函数,用于将组件注入您的 worker class。

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() {

    }
}

我正在使用 these 系列 post 在我的应用中实现 Dagger 和 ProfileManager 是 class 我想 inject 在我的 Worker class.

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 class 我在 Provider class

中设置 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;
    }

}

App组件

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

}