我正在使用MVVM架构,并使用Dagger2进行数据注入。我遇到的问题是,在Activity / Fragments中,@Inject正常工作,但在WorkManager的Worker类中,@Inject在运行时会出现空指针异常。我该如何解决?
以下是Worker类代码:
以下是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();
}
myComponent.inject(mySyncManager)
?请包含注入工作者的代码。 - David Medenjak