我想用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()
}
}
}
HiltAndroidAppIs:
@HiltAndroidApp
class AppInstance : Application(), Configuration.Provider{
@Inject lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
}
在我添加的manifest文件中:
<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条答案
按热度按时间epfja78i1#
可能是因为documentation
定期工作的最小间隔为15分钟。
你不能每隔1秒就有一个周期性的工作请求,所以你的代码可能正在工作,你只是没有等待15分钟来触发它。