微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐