class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val workManager1 : WorkRequest = PeriodicWorkRequestBuilder<WorkManager1>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(this).enqueue(workManager1)
}
}
class WorkManager1 (val context: Context, workerParams: WorkerParameters): Worker(context, workerParams) {
override fun doWork(): Result {
Log.d("WorkManager1", "doWork")
for(i in 0..10){
Thread.sleep(1000)
Log.d("WorkManager1", i.toString())
}
saveLogAsFile(context, "workManager Log")
return Result.success()
}
fun saveLogAsFile(context: Context, saveText : String){
val randomUuid = UUID.randomUUID()
val cFormat = SimpleDateFormat("hh:mm:ss")
val currentDate = cFormat.format(Date())
val file:String = currentDate
val data:String = saveText
val fileOutputStream: FileOutputStream
try {
fileOutputStream = context.openFileOutput("$file $randomUuid", Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
} catch (e: FileNotFoundException){
e.printStackTrace()
}catch (e: NumberFormatException){
e.printStackTrace()
}catch (e: IOException){
e.printStackTrace()
}catch (e: Exception){
e.printStackTrace()
}
}
}
https://stackoverflow.com/questions/51202905/execute-task-every-second-using-work-manager-api
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/define-work?hl=ko
'Android Jetpack' 카테고리의 다른 글
Coroutine flow (0) | 2022.06.19 |
---|---|
WorkManager 고유작업 (0) | 2022.05.15 |
Retrofit + ViewModelScope + RecyclerView + Glide Example (0) | 2022.04.20 |
Retrofit Simple Example RecyclerView 추가 (0) | 2022.04.18 |
기존 예제 변경 (0) | 2022.04.17 |