我想使用 Dagger Hilt 依赖注入运行PeriodicWork。但是,它不会定期工作。我已经检查过我的代码很多次了。尽管我希望每秒收到一条消息,但最多只有一条成功完成工作的消息。
这是 MainActivity 的代码:
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RunARepeatableWorkUsingWorkManagerTheme {
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(key1 = Unit ){
val workRequest = PeriodicWorkRequestBuilder<CustomWorker>(
repeatInterval = 1,
repeatIntervalTimeUnit = TimeUnit.SECONDS,)
.setBackoffCriteria(
backoffPolicy = BackoffPolicy.LINEAR,
duration = Duration.ofSeconds(5))
.build()
val workManager = WorkManager.getInstance(applicationContext)
workManager.enqueueUniquePeriodicWork("myWork", ExistingPeriodicWorkPolicy.KEEP, workRequest)
workManager.getWorkInfosForUniqueWorkLiveData("myWork")
.observe(lifecycleOwner){ it ->
it.forEach {workInfo ->
Log.d("MyWorker: MainActivity", "${workInfo.state}")
}
}
}
}
}
}
}
我的工人看起来像这样:
@HiltWorker
class CustomWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters){
override suspend fun doWork(): Result {
try {
println("MyWorker : The result or the worker is Success")
return Result.success()
} catch (e: Exception) {
Log.e("MyWorker: CustomWorker", "Worker failed: ${e.message}", e)
return Result.failure()
}
}
}
HiltAndroidApp是:
@HiltAndroidApp
class AppInstance : Application(), Configuration.Provider{
@Inject lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
}
另外,我在清单文件中添加了:
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge"
>
<meta-data
android:name="androidx.work.impl.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
Logcat 仅显示:
2023-09-24 18:16:46.712 4819-4819 MyWorker: MainActivity com...epeatableworkusingworkmanager D ENQUEUED
2023-09-24 18:17:47.375 4819-4854 System.out com...epeatableworkusingworkmanager I MyWorker : The result or the worker is Success
2023-09-24 18:17:47.429 4819-4819 MyWorker: MainActivity com...epeatableworkusingworkmanager D RUNNING
2023-09-24 18:17:47.437 4819-4819 MyWorker: MainActivity com...epeatableworkusingworkmanager D ENQUEUED
就这样。问题是:为什么我看不到每秒都在完成工作的消息?我将不胜感激任何帮助!
可能是因为根据文档
您不可能每 1 秒就有一个定期工作请求,因此您的代码可能正在工作,您只是不需要等待 15 分钟来触发它。