我正在开发一个 Android 应用程序。我正在尝试将 hilt 与 workmanager 构造函数一起使用,但它不起作用并给了我这个错误:
2020-08-18 19:01:09.989 18125-18759/com. E/WM-WorkerFactory: Could not instantiate example.android.app.database.DeleteNotesWorker
java.lang.NoSuchMethodException: example.android.app.database.DeleteNotesWorker.<init> [class android.content.Context, class androidx.work.WorkerParameters]
at java.lang.Class.getConstructor0(Class.java:2328)
at java.lang.Class.getDeclaredConstructor(Class.java:2167)
at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:95)
at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:242)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
这是工人阶级:
class DeleteNotesWorker @WorkerInject constructor(
@Assisted context: Context,
@Assisted workerParams: WorkerParameters,
private val dao : NotesDao
) : CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
dao.deleteNotesInTrash()
return Result.success()
}
}
应用模块:
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun getNotesDatabase(@ApplicationContext context: Context) =
Room.databaseBuilder(context, NotesDatabase::class.java, NotesDatabase.DB_NAME).build()
@Singleton
@Provides
fun getDoa(db: NotesDatabase) = db.notesDao()
}
应用类:
@HiltAndroidApp
class App : Application(), Configuration.Provider {
@Inject
lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration(): Configuration {
return Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
}
}
build.gradle(应用程序):
dependencies {
.......
//Hilt
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
//Hilt with workManager
implementation 'androidx.hilt:hilt-work:1.0.0-alpha02'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'
}
build.gradle(项目):
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
............
//Hilt
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
..........
}
在这种情况下我做错了什么吗?如果是,请帮助我