我如何处理完成的工作 OneTimeWorkRequest?
How can I handle finished work OneTimeWorkRequest?
大家好。正如标题所暗示的,我需要在 WorkManager 完成它的工作(每 60 秒)时抽出时间来执行其他操作。目前我知道我不能将它用于少于 15 分钟的工作,但通过尝试一些不同的方法我可以解决这个问题。但事实仍然是我需要弄清楚 OneTimeWorkRequest 命令计时器何时结束。你有什么建议给我?
这是我的代码:
主要活动:
class MAinActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setPeriodicallySendingLogs()
}
private fun setPeriodicallySendingLogs() {
val workManager = WorkManager.getInstance(this)
val sendingLog = PeriodicWorkRequestBuilder<SendLogWorker>(15, TimeUnit.MINUTES)
.build()
workManager.enqueue(sendingLog)
workManager.getWorkInfoByIdLiveData(sendingLog.id)
.observe(this, Observer { workInfo ->
Log.d("WM", " info${workInfo.state.name}")
})
}
}
工人:
class SendLogWorker(private val context: Context, userParameters: WorkerParameters) :
Worker(context, userParameters) {
override fun doWork(): Result {
val mywork = OneTimeWorkRequest.Builder(SendLogWorker::class.java)
.setInitialDelay(1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context).enqueue(mywork)
return Result.success()
}
}
workManager.getWorkInfoByIdLiveData(syncWorker.id)
.observe(getViewLifecycleOwner(), workInfo -> {
if (workInfo.getState() != null &&
workInfo.getState() == WorkInfo.State.SUCCEEDED) {
Snackbar.make(requireView(),
R.string.work_completed, Snackbar.LENGTH_SHORT)
.show();
}
});
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/managing-work
大家好。正如标题所暗示的,我需要在 WorkManager 完成它的工作(每 60 秒)时抽出时间来执行其他操作。目前我知道我不能将它用于少于 15 分钟的工作,但通过尝试一些不同的方法我可以解决这个问题。但事实仍然是我需要弄清楚 OneTimeWorkRequest 命令计时器何时结束。你有什么建议给我? 这是我的代码:
主要活动:
class MAinActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setPeriodicallySendingLogs()
}
private fun setPeriodicallySendingLogs() {
val workManager = WorkManager.getInstance(this)
val sendingLog = PeriodicWorkRequestBuilder<SendLogWorker>(15, TimeUnit.MINUTES)
.build()
workManager.enqueue(sendingLog)
workManager.getWorkInfoByIdLiveData(sendingLog.id)
.observe(this, Observer { workInfo ->
Log.d("WM", " info${workInfo.state.name}")
})
}
}
工人:
class SendLogWorker(private val context: Context, userParameters: WorkerParameters) :
Worker(context, userParameters) {
override fun doWork(): Result {
val mywork = OneTimeWorkRequest.Builder(SendLogWorker::class.java)
.setInitialDelay(1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context).enqueue(mywork)
return Result.success()
}
}
workManager.getWorkInfoByIdLiveData(syncWorker.id)
.observe(getViewLifecycleOwner(), workInfo -> {
if (workInfo.getState() != null &&
workInfo.getState() == WorkInfo.State.SUCCEEDED) {
Snackbar.make(requireView(),
R.string.work_completed, Snackbar.LENGTH_SHORT)
.show();
}
});
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/managing-work