ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Android] Background Task1 : WorkManager 개념 및 예제
    Android & Kotlin 2022. 6. 7. 02:01

    📍 Android 에서의 Background의 의미

    안드로이드에서의 Background 는 말 그대로 눈에 보이지 않는 곳에서의 작업을 말한다.

    Activity 를 예로 들면 onResume 부터 onPause 까지에서의 작업을 를 Foreground 작업

    그 이외 사용자에게 보이지 않는 상태에서의 작업을 Background 작업이라고 할 수 있다.

     

    📌 BackgroundTask 구분하기

    작업에 대해 어떤 Background 솔루션을 사용할지를 고민해볼 필요가 있다.

     

    기존에 FirebaseJobDispatcher, GcmNetworkManager, Job Scheduler 등 이전 백그라운드 Api 를 WorkManager가 대체하게 되었다.

     

    현재는 백그라운드 작업에 대해 WorkManager, Alarm Manager, Service, CoRoutine 이렇게 4가지 솔루션들을 그 상황에 맞게 선택해서 사용해야한다고 생각한다.

     

    주의) Forground 상황에서 WorkManager 는 즉각적 피드백을 주지만 Background 상황에서는 이를 보장하지 못한다.

     

    if ( 정확한 시간에 대한 피드백이 필요하진 않지만 실행이 보장되어야하는 경우 ) -> WorkManager
    else if ( 즉각적인 피드백 필요 하며 중단이 발생하지 않는 경우 ) -> Foreground Service
    else if ( 정확한 시간에 대한 피드백이 필요한 경우) -> Alarm Manager

     

     

     

    📌 WorkManager 특징

    • 작업 제약 조건 - 네트워크 가용성, 충전상태와 같은 작업의 조건을 설정할 수 있다.
    • 예약 관리 - 일회성, 주기적 비동기 작업을 예약할 수 있다
    • 유연한 재시도 - 앱이 종료되거나 기기가 다시 시작되는 경우에도 안정적으로 실행되도록 설계되어 있다.
      • 완료 시점에 대한 보장은 하지 않는다.
    • 작업 체이닝 - 개별 작업들을 체이닝하여 순차적 혹은 병렬적 실행을 명령할 수 있습니다.

     

    📌 WorkManager 예제

    WorkManager 와 BroadcastReciver 를 조합해 파일을 다운로드하고 알림을 받을 수 있는 기능을 구현해보았습니다.

     

    1. Worker 정의

    class CertificationWorker(private val appContext: Context, workerParameters: WorkerParameters) :
        Worker(appContext, workerParameters) {
        override fun doWork(): Result {
     
                downloadCertification()
    
                // 리시버 등록
                val receiver = DownloadBroadcastReceiver()
                val filter = IntentFilter("MyAction")
    
                // 브로드케스트 발송
                Intent().also {
                    it.setAction("MyAction")
                        .setPackage("com.example.airbnb")
                    appContext.sendBroadcast(it)
                }
        }

     

    2. 작업 요청

    // Fragment
    
     private fun listenDownloadButtonClick() {
            binding.btnDownload.setOnClickListener {
                val testWork: WorkRequest = OneTimeWorkRequest.from(CertificationWorker::class.java)
                val workManger = WorkManager.getInstance(requireContext())
                    .enqueue(testWork)
            }
        }

     

    3. 리시버 정의

    class DownloadBroadcastReceiver : BroadcastReceiver() {
    
        override fun onReceive(context: Context, intent: Intent) {
            if (isAppInForegrounded()) {
                Toast.makeText(
                    context,
                    context.getString(R.string.notification_download_completed),
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                val builder = NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_baseline_hotel_24)
                    .setContentTitle(context.getString(R.string.notification_down_completed_title))
                    .setContentText(context.getString(R.string.notification_download_completed))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    
                showNotification(context, builder)
            }
        }
    }

    댓글

Designed by Tistory.