【ANDROID STUDIO】Periodic Work Request Work Manager

 package com.example.wordmanager


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

companion object {
const val KEY_COUNT_VALUE = "key_count"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
//setOneTimeWorkRequest()
setPeriodicWorkRequest()
}

}

private fun setPeriodicWorkRequest() {
val periodicWorkRequest = PeriodicWorkRequest.Builder(DownloadingWorker::class.java,16,
TimeUnit.MINUTES)
.build()
WorkManager.getInstance(applicationContext).enqueue(periodicWorkRequest)
}

private fun setOneTimeWorkRequest() {
val workManager = WorkManager.getInstance(applicationContext)
val data: Data = Data.Builder()
.putInt(KEY_COUNT_VALUE,125)
.build()
val constraints = Constraints.Builder()
.setRequiresCharging(true)
.build()
val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java)
.setConstraints(constraints)
.setInputData(data)
.build()
val filteringRequest = OneTimeWorkRequest.Builder(FilteringWorker::class.java)
.build()
val compressingRequest= OneTimeWorkRequest.Builder(CompressingWorker::class.java)
.build()
val downloadingWorker= OneTimeWorkRequest.Builder(DownloadingWorker::class.java)
.build()
val paralleWorks = mutableListOf<OneTimeWorkRequest>()
paralleWorks.add(downloadingWorker)
paralleWorks.add(filteringRequest)
workManager
.beginWith(paralleWorks)
.then(compressingRequest)
.then(uploadRequest)
.enqueue()
workManager.getWorkInfoByIdLiveData(uploadRequest.id)
.observe(this, Observer {
textView.text = it.state.name
if(it.state.isFinished) {
val data = it.outputData
val message = data.getString(UploadWorker.KEY_WORKER)
Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
}
})
}

}
package com.example.wordmanager

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*

class DownloadingWorker(context: Context, params: WorkerParameters) : Worker(context,params) {


override fun doWork(): Result {
try {

for (i in 0..300) {
Log.i("MYTAG", "Downloading $i")
}

val time = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = time.format(Date())
Log.i("MYTAG","Completed $currentDate")

return Result.success()
} catch (e: Exception) {
return Result.failure()
}
}

}

No comments:

My New Favorite Music Genre Is Polish Noir

These 10 artists create music that is mystical, melancholy, magical, and more. ͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏    ...

Contact Form

Name

Email *

Message *