Search code examples
androidkotlinandroid-workmanager

How can I handle finished work OneTimeWorkRequest?


Hi everyone. As the title suggests, I need to take the time when WorkManager finishes its work (every 60 seconds) to perform other operations. At the moment I know that I can't use it for jobs less than 15 minutes, but by trying some different way I can get around the problem. But the fact remains that I need to figure out when the OneTimeWorkRequest command timer ends. What do you suggest to me? Here my code:

MainActivity:

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

Worker:

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

Solution

  • 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