Coroutine Worker

최희창·2022년 6월 20일
0

Android AAC

목록 보기
7/13

CoroutineWorker 사용해보기

  • WorkManager + Coroutine으로 매일 특정시간에 Notification 띄우는 것을 구현해보자.
  • CoroutineWorker : Coroutine을 이용한 WorkManager
class ExampleCoroutineWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params) {
 
    override suspend fun doWork(): Result = coroutineScope {
                withContext(Dispatchers.IO) {
                //TODO    
        }
 
        Result.success()
    }
}

OneTimeWorkRequest 요청

  • OneTimeWorkRequest을 통해서 ExampleCoroutineWorker을 호출하는 요청을 한다.
private fun initWorkManager() {
        val dailyWorkRequeset = OneTimeWorkRequestBuilder<ExampleCoroutineWorker>()
        .setInitialDelay(getTimeUsingInWorkRequest(), TimeUnit.MILLISECONDS)
        .addTag("notify_day_by_day")
        .build()
 
 
    WorkManager.getInstance(this).enqueue(dailyWorkRequeset)
}
fun getTimeUsingInWorkRequest() : Long {
        val currentDate = Calendar.getInstance()
        val dueDate = Calendar.getInstance()
 
        dueDate.set(Calendar.HOUR_OF_DAY, 0)
        dueDate.set(Calendar.MINUTE, 10)
        dueDate.set(Calendar.SECOND, 0)
 
        if(dueDate.before(currentDate)) {
                dueDate.add(Calendar.HOUR_OF_DAY, 24)
        }
 
        return dueDate.timeInMillis - currentDate.timeInMillis
}
profile
heec.choi

0개의 댓글