3

我正在研究 MVVM 架构,并且正在使用 Dagger2 进行数据注入。我面临的问题是在 Activity/Fragments 中 @Inject 工作正常,但在 WorkManager 的 Worker 类中,@Inject 在运行时给出空指针异常。我该如何解决?

以下是 Worker 类代码:

public class MySyncManager extends Worker {

    @Inject
    DataManager dataManager;

    @Inject
    SchedulerProvider schedulerProvider;

    @NonNull
    @Override
    public WorkerResult doWork() {

        CommonUtils.Log("usm_work_manager_1", "Work is Started.");
         if(dataManager==null) 
        CommonUtils.Log("usm_work_manager", "Injector is NULL");

    }
    }

方法:

    private void startTestSyncRequest() {
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MySyncManager.class)
                .setConstraints(myConstraints)
                .setInitialDelay(1, TimeUnit.SECONDS)  // wait for n seconds before starting service
                .build();

        WorkManager.getInstance()
                .beginUniqueWork(Tags.TEST_WORK_NAME, ExistingWorkPolicy.REPLACE, workRequest)
                .enqueue();

}
4

4 回答 4

5

要首先在工作类中注入字段,您需要在 AppComponent 中注入工作类:

 fun inject(syncItemWorker: SyncItemWorker)

然后在工人的 doWork() 中,您需要调用注入:

 if(applicationContext is MyApp){
        var daggerAppComponent= DaggerAppComponent.builder().application(applicationContext as MyApp).build()
        daggerAppComponent.inject(this)
    }
于 2018-05-31T20:22:29.270 回答
0

他们仍然没有对 WorkManager 的内部支持。它可能会出现在一个新的工件 ( dagger-android-work) 中,并支持@ContributesAndroidInjector.

但是我们可以创建自己的一切来完成它。按照下面的代码。

应用组件.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 中注入所有依赖项。快乐编码!

于 2019-02-12T12:32:50.323 回答
0

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

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

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

    void inject(MySyncManager mySyncManager);
}

模块类

@Module
public class Module{

    @Provides
    public DataManager provideDataManager(){
        return new DataManager();
    }

    @Provides
    public SchedulerProvider provideSchedulerProvider(){
        return new SchedulerProvider();
    }

}

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

public class MySyncManager extends  Worker {

    @Inject
    DataManager dataManager;

    @Inject
    SchedulerProvider schedulerProvider;

    public MySyncManager(){
        DaggerComponent1.builder().build().inject();
    }

    @NonNull
    @Override
    public Result doWork() {

        sync();
        return Result.SUCCESS;
    }

    private void sync() {

    }
}

这个答案是从这个SO帖子复制的,你可以检查一下

于 2018-08-19T08:12:04.837 回答
-1

考虑到构造函数注入,不建议使用字段注入。这是构造函数注入的一个很好的示例,请查看此博客。基本上你可以像这样注入:

@AssistedInject
public PrePopulateDataWorker(@Assisted @NonNull Context context, @Assisted @NonNull WorkerParameters workerParams, DataManager dataManager) {
    super(context, workerParams);
    this.dataManager = dataManager;
}

@AssistedInject.Factory
public interface Factory extends CustomWorkerFactory {}

这里的实例DataManger被注入。是Java实现

于 2019-03-20T14:37:41.033 回答