깨알 개념/Android

[Android] WorkManager - 인자 전달 및 데이터 반환

interfacer_han 2024. 6. 17. 20:09

#1 이전 글

 

[Android] WorkManager - 기초

#1 이전 글 [Android] WorkManager - 개요#1 WorkManager는 '지연 가능한 백그라운드 작업'의 관리자 WorkManager를 사용한 백그라운드 작업 - Kotlin | Android DevelopersAndroid에는 보장된 백그라운드 작업을 위한 다

kenel.tistory.com

위 게시글의 완성된 앱을 일부 수정해서, Worker에 인자를 전달하고 Worker로부터 데이터를 반환받아 본다.

 

#2 코드 수정

#2-1 MainActivity - setOneTimeWorkRequest()

...

class MainActivity : AppCompatActivity() {

    companion object {
        const val KEY_LUCKY_NUMBER= "key_lucky"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
    }

    private fun setOneTimeWorkRequest() {
        // Worker에 전달할 Data 객체 만들기
        val inputData: Data = Data
            .Builder()
            .putInt(KEY_LUCKY_NUMBER, 777)
            .build()

        // WorkRequest 객체 만들기
        val uploadRequest = OneTimeWorkRequest
            .Builder(UploadWorker::class.java)
            .setInputData(inputData)
            .build()

        // WorkManager 객체의 작업 큐(Job queue)에 WorkRequest 등록
        ...

        // WorkInfo는 작업에 대한 정보를 담은 객체.
        // WorkManager.getWorkInfoByIdLiveData()는 LiveData<WorkInfo>를 반환.
        ...
        workInfo.observe(this, Observer {
            ...

            if(it.state.name == "SUCCEEDED") {
                val outputData = it.outputData
                Log.i("interfacer_han", "(${this::class.simpleName}) UploadWorker's output: ${outputData.getString(UploadWorker.KEY_UPLOAD_WORKER)}")
            }
        })
    }

    private fun setPeriodicWorkRequest() {
        ...
    }
}

WorkManager에선 인자의 전달 및 데이터 반환을 androidx.work.Data로 한다. androidx.work.Data를 import하고 Data 객체를 만들어 Request에 넣는다. 그리고 LiveData.observe() 부분을 위와 같이 수정한다. WorkInfo.outputData는 WorkRequest가 끝나기 전에는 아무런 값이 들어있지 않다. 따라서 if문을 넣어 상태를 확인한다.

 

#2-2 MainActivity - setPeriodicWorkRequest()

...

class MainActivity : AppCompatActivity() {

    companion object {
        const val KEY_LUCKY_NUMBER= "key_lucky"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
    }

    private fun setOneTimeWorkRequest() {
        ...
    }

    private fun setPeriodicWorkRequest() {
        // Worker에 전달할 Data 객체 만들기
        val inputData: Data = Data
            .Builder()
            .putInt(KEY_LUCKY_NUMBER, 777)
            .build()

        // WorkRequest 객체 만들기
        val downloadRequest = PeriodicWorkRequest
            .Builder(DownloadWorker::class.java, 15, TimeUnit.MINUTES) // 안드로이드에서 허용하는 PeriodicWorkRequest의 최소 주기는 15분이다.
            .setInputData(inputData)
            .build()

        // WorkManager 객체의 작업 큐(Job queue)에 WorkRequest 등록
        ...

        // WorkInfo는 작업에 대한 정보를 담은 객체.
        // WorkManager.getWorkInfoByIdLiveData()는 LiveData<WorkInfo>를 반환.
        ...
        workInfo.observe(this, Observer {
            ...

            // 이 if문 속의 코드는 영원히 실행되지 못한다.
            if(it.state.name == "SUCCEEDED") {
                val outputData = it.outputData
                Log.i("interfacer_han", "(${this::class.simpleName}) DownloadWorker's output: ${outputData.getString(DownloadWorker.KEY_DOWNLOAD_WORKER)}")
            }
        })
    }
}

#2-1과 같은 맥락으로 코드를 수정한다. 하지만, #2-1에서와는 달리 setPeriodicWorkRequest()에서는 데이터를 반환받을 수 없다. 왜냐하면 PeriodicWorkRequest는 끝나지 않기 때문이다 (이 게시글의 #4-3 참조). WorkInfo.outputData는 WorkRequest가 끝나기 전에는 아무런 값이 들어있지 않다. 따라서 WorkInfo.outputData는 항상 비어있게 된다. 결론적으로 PeriodicWorkRequest로부터는 데이터를 반환받을 것을 기대할 수 없으며, 해당 Request에 들어있는 Worker에서 직접 데이터베이스 등에 값을 넣는 식으로 우회해야 한다.

 

#2-3 UploadWorker.kt

// package com.example.argumentsandreturn

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

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

    companion object {
        const val KEY_UPLOAD_WORKER = "key_upload_worker"
    }

    override fun doWork(): Result {
        try {
            Log.i(...)

            val inputtedData = inputData.getInt(MainActivity.KEY_LUCKY_NUMBER, -1)
            Log.i(...)

            for (i in 0..100) {
                ...
            }

            val outputData = Data
                .Builder()
                .putString(KEY_UPLOAD_WORKER, "Hello, MainActivity! I'm UploadWorker")
                .build()

            Log.i(...)
            return Result.success(outputData)

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

    ...
}

#2-1와 방향만 반대라고 보면 된다.

 

#2-4 DownloadWorker.kt

...

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

    companion object {
        const val KEY_DOWNLOAD_WORKER = "key_download_worker"
    }

    override fun doWork(): Result {
        try {
            ...

            val outputData = Data
                .Builder()
                .putString(KEY_DOWNLOAD_WORKER, "Hello, MainActivity! I'm DownloadWorker.")
                .build()

            ...
            return Result.success(outputData)

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

    ...
}

상수 부분과 putString() 부분을 제외하고, #2-3과 완전히 동일하게 수정한다.

 

#3 작동 확인

#3-1 'One Time Request' 버튼을 클릭했을 때의 로그 메시지

더보기
(MainActivity) UploadWorker's state: ENQUEUED
(UploadWorker) Started at 2024/06/17 08:31:33
(UploadWorker) Inputted data: 777
(UploadWorker) Progress: 0/100
(UploadWorker) Progress: 1/100
(UploadWorker) Progress: 2/100
(UploadWorker) Progress: 3/100
(UploadWorker) Progress: 4/100
(UploadWorker) Progress: 5/100
(UploadWorker) Progress: 6/100
(UploadWorker) Progress: 7/100
(UploadWorker) Progress: 8/100
(UploadWorker) Progress: 9/100
(UploadWorker) Progress: 10/100
(UploadWorker) Progress: 11/100
(UploadWorker) Progress: 12/100
(UploadWorker) Progress: 13/100
(MainActivity) UploadWorker's state: RUNNING
(UploadWorker) Progress: 14/100
(UploadWorker) Progress: 15/100
(UploadWorker) Progress: 16/100
(UploadWorker) Progress: 17/100
(UploadWorker) Progress: 18/100
(UploadWorker) Progress: 19/100
(UploadWorker) Progress: 20/100
(UploadWorker) Progress: 21/100
(UploadWorker) Progress: 22/100
(UploadWorker) Progress: 23/100
(UploadWorker) Progress: 24/100
(UploadWorker) Progress: 25/100
(UploadWorker) Progress: 26/100
(UploadWorker) Progress: 27/100
(UploadWorker) Progress: 28/100
(UploadWorker) Progress: 29/100
(UploadWorker) Progress: 30/100
(UploadWorker) Progress: 31/100
(UploadWorker) Progress: 32/100
(UploadWorker) Progress: 33/100
(UploadWorker) Progress: 34/100
(UploadWorker) Progress: 35/100
(UploadWorker) Progress: 36/100
(UploadWorker) Progress: 37/100
(UploadWorker) Progress: 38/100
(UploadWorker) Progress: 39/100
(UploadWorker) Progress: 40/100
(UploadWorker) Progress: 41/100
(UploadWorker) Progress: 42/100
(UploadWorker) Progress: 43/100
(UploadWorker) Progress: 44/100
(UploadWorker) Progress: 45/100
(UploadWorker) Progress: 46/100
(UploadWorker) Progress: 47/100
(UploadWorker) Progress: 48/100
(UploadWorker) Progress: 49/100
(UploadWorker) Progress: 50/100
(UploadWorker) Progress: 51/100
(UploadWorker) Progress: 52/100
(UploadWorker) Progress: 53/100
(UploadWorker) Progress: 54/100
(UploadWorker) Progress: 55/100
(UploadWorker) Progress: 56/100
(UploadWorker) Progress: 57/100
(UploadWorker) Progress: 58/100
(UploadWorker) Progress: 59/100
(UploadWorker) Progress: 60/100
(UploadWorker) Progress: 61/100
(UploadWorker) Progress: 62/100
(UploadWorker) Progress: 63/100
(UploadWorker) Progress: 64/100
(UploadWorker) Progress: 65/100
(UploadWorker) Progress: 66/100
(UploadWorker) Progress: 67/100
(UploadWorker) Progress: 68/100
(UploadWorker) Progress: 69/100
(UploadWorker) Progress: 70/100
(UploadWorker) Progress: 71/100
(UploadWorker) Progress: 72/100
(UploadWorker) Progress: 73/100
(UploadWorker) Progress: 74/100
(UploadWorker) Progress: 75/100
(UploadWorker) Progress: 76/100
(UploadWorker) Progress: 77/100
(UploadWorker) Progress: 78/100
(UploadWorker) Progress: 79/100
(UploadWorker) Progress: 80/100
(UploadWorker) Progress: 81/100
(UploadWorker) Progress: 82/100
(UploadWorker) Progress: 83/100
(UploadWorker) Progress: 84/100
(UploadWorker) Progress: 85/100
(UploadWorker) Progress: 86/100
(UploadWorker) Progress: 87/100
(UploadWorker) Progress: 88/100
(UploadWorker) Progress: 89/100
(UploadWorker) Progress: 90/100
(UploadWorker) Progress: 91/100
(UploadWorker) Progress: 92/100
(UploadWorker) Progress: 93/100
(UploadWorker) Progress: 94/100
(UploadWorker) Progress: 95/100
(UploadWorker) Progress: 96/100
(UploadWorker) Progress: 97/100
(UploadWorker) Progress: 98/100
(UploadWorker) Progress: 99/100
(UploadWorker) Progress: 100/100
(UploadWorker) Finished at 2024/06/17 08:31:33
(MainActivity) UploadWorker's state: SUCCEEDED
(MainActivity) UploadWorker's output: Hello, MainActivity! I'm UploadWorker

 

 

#3-2 'Periodic Request' 버튼을 클릭했을 때의 로그 메시지

더보기
(MainActivity) DownloadWorker's state: ENQUEUED
(DownloadWorker) Started at 2024/06/17 08:33:28
(DownloadWorker) Inputted data: 777
(DownloadWorker) Progress: 0/100
(DownloadWorker) Progress: 1/100
(DownloadWorker) Progress: 2/100
(DownloadWorker) Progress: 3/100
(DownloadWorker) Progress: 4/100
(DownloadWorker) Progress: 5/100
(DownloadWorker) Progress: 6/100
(DownloadWorker) Progress: 7/100
(DownloadWorker) Progress: 8/100
(DownloadWorker) Progress: 9/100
(DownloadWorker) Progress: 10/100
(DownloadWorker) Progress: 11/100
(DownloadWorker) Progress: 12/100
(DownloadWorker) Progress: 13/100
(DownloadWorker) Progress: 14/100
(DownloadWorker) Progress: 15/100
(DownloadWorker) Progress: 16/100
(DownloadWorker) Progress: 17/100
(DownloadWorker) Progress: 18/100
(DownloadWorker) Progress: 19/100
(DownloadWorker) Progress: 20/100
(DownloadWorker) Progress: 21/100
(DownloadWorker) Progress: 22/100
(DownloadWorker) Progress: 23/100
(DownloadWorker) Progress: 24/100
(DownloadWorker) Progress: 25/100
(DownloadWorker) Progress: 26/100
(DownloadWorker) Progress: 27/100
(DownloadWorker) Progress: 28/100
(DownloadWorker) Progress: 29/100
(DownloadWorker) Progress: 30/100
(DownloadWorker) Progress: 31/100
(DownloadWorker) Progress: 32/100
(DownloadWorker) Progress: 33/100
(DownloadWorker) Progress: 34/100
(DownloadWorker) Progress: 35/100
(DownloadWorker) Progress: 36/100
(DownloadWorker) Progress: 37/100
(DownloadWorker) Progress: 38/100
(DownloadWorker) Progress: 39/100
(DownloadWorker) Progress: 40/100
(DownloadWorker) Progress: 41/100
(DownloadWorker) Progress: 42/100
(DownloadWorker) Progress: 43/100
(DownloadWorker) Progress: 44/100
(DownloadWorker) Progress: 45/100
(DownloadWorker) Progress: 46/100
(DownloadWorker) Progress: 47/100
(DownloadWorker) Progress: 48/100
(DownloadWorker) Progress: 49/100
(DownloadWorker) Progress: 50/100
(DownloadWorker) Progress: 51/100
(DownloadWorker) Progress: 52/100
(DownloadWorker) Progress: 53/100
(DownloadWorker) Progress: 54/100
(DownloadWorker) Progress: 55/100
(DownloadWorker) Progress: 56/100
(DownloadWorker) Progress: 57/100
(DownloadWorker) Progress: 58/100
(DownloadWorker) Progress: 59/100
(DownloadWorker) Progress: 60/100
(DownloadWorker) Progress: 61/100
(DownloadWorker) Progress: 62/100
(DownloadWorker) Progress: 63/100
(DownloadWorker) Progress: 64/100
(DownloadWorker) Progress: 65/100
(DownloadWorker) Progress: 66/100
(DownloadWorker) Progress: 67/100
(DownloadWorker) Progress: 68/100
(DownloadWorker) Progress: 69/100
(DownloadWorker) Progress: 70/100
(DownloadWorker) Progress: 71/100
(DownloadWorker) Progress: 72/100
(DownloadWorker) Progress: 73/100
(MainActivity) DownloadWorker's state: RUNNING
(DownloadWorker) Progress: 74/100
(DownloadWorker) Progress: 75/100
(DownloadWorker) Progress: 76/100
(DownloadWorker) Progress: 77/100
(DownloadWorker) Progress: 78/100
(DownloadWorker) Progress: 79/100
(DownloadWorker) Progress: 80/100
(DownloadWorker) Progress: 81/100
(DownloadWorker) Progress: 82/100
(DownloadWorker) Progress: 83/100
(DownloadWorker) Progress: 84/100
(DownloadWorker) Progress: 85/100
(DownloadWorker) Progress: 86/100
(DownloadWorker) Progress: 87/100
(DownloadWorker) Progress: 88/100
(DownloadWorker) Progress: 89/100
(DownloadWorker) Progress: 90/100
(DownloadWorker) Progress: 91/100
(DownloadWorker) Progress: 92/100
(DownloadWorker) Progress: 93/100
(DownloadWorker) Progress: 94/100
(DownloadWorker) Progress: 95/100
(DownloadWorker) Progress: 96/100
(DownloadWorker) Progress: 97/100
(DownloadWorker) Progress: 98/100
(DownloadWorker) Progress: 99/100
(DownloadWorker) Progress: 100/100
(DownloadWorker) Finished at 2024/06/17 08:33:28
(MainActivity) DownloadWorker's state: ENQUEUED

이하 생략

 

#4 요약

끝나는 게 가능한 WorkRequest에게서만 데이터를 직접 반환받을 수 있다.

 

#5 완성된 앱

 

android-practice/work-manager/ArgumentsAndReturn at master · Kanmanemone/android-practice

Contribute to Kanmanemone/android-practice development by creating an account on GitHub.

github.com