android-无法在WorkManager的Worker类中注入单例类
作者:互联网
我正在研究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();
}
解决方法:
在工人阶级中注入领域
首先,您需要将您的worker类注入AppComponent内:
fun inject(syncItemWorker: SyncItemWorker)
然后在worker的doWork()中,您需要调用inject:
if(applicationContext is MyApp){
var daggerAppComponent= DaggerAppComponent.builder().application(applicationContext as MyApp).build()
daggerAppComponent.inject(this)
}
标签:dagger-2,dependency-injection,android-workmanager,android 来源: https://codeday.me/bug/20191025/1926401.html