我正在研究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) }
总结 以上是内存溢出为你收集整理的android-无法在WorkManager的Worker类中注入单例类全部内容,希望文章能够帮你解决android-无法在WorkManager的Worker类中注入单例类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)