안드로이드 백그라운드 정책 - 버전별 차이 및 WorkManager

2019. 8. 23. 17:08Development/[Android] 안드로이드

728x90

    안드로이드의 버전별 백그라운드 정책은 공식 문서에 아래와 같이 정의하고 있습니다. (https://developer.android.com/guide/background/#challenges_in_background_processing)

  • Android 6.0 (API level 23) introduced Doze mode and app standby. Doze mode restricts app behavior when the screen is off and the device is stationary. App standby puts unused applications into a special state that restricts their network access, jobs, and syncs.
  • Android 7.0 (API level 24) limited implicit broadcasts and introduced Doze-on-the-Go.
  • Android 8.0 (API level 26) further limited background behavior, such as getting location in the background and releasing cached wakelocks.
  • Android 9 (API level 28) introduced App Standby Buckets, in which app requests for resources are dynamically prioritized based on app usage patterns.

    번역을 하자면 다음과 같습니다.

    - Android 6.0 (API 레벨 23)에는 Doze 모드 및 앱 대기가 도입되었습니다. Doze 모드는 화면이 꺼져 있고 장치가 정지 된 경우 앱 동작을 제한합니다. 앱 대기는 사용하지 않는 애플리케이션을 네트워크 액세스, 작업 및 동기화를 제한하는 특수 상태로 만듭니다.

     *. Doze 모드 : 기기가 전원 공급 장치에 연결되어 있지 않으면 앱이 작동하는 방식을 관리하여 배터리 수명을 연장할 수 있도록 하는데, 백그라운드 CPU 및 네트워크 활동을 지연시킵니다. 자세한 사항은 https://developer.android.com/training/monitoring-device-state/doze-standby?hl=ko 참조    


    - Android 7.0 (API 레벨 24)은 암시적 브로드 캐스트를 제한하고 Doze-on-the-Go를 도입했습니다.
    - Android 8.0 (API 레벨 26)은 백그라운드에서 위치를 가져오고 캐시된 웨이크 록을 해제하는 등 백그라운드 동작을 더욱 제한했습니다.
    - Android 9 (API 레벨 28)에는 앱 사용 패턴을 기반으로 리소스에 대한 앱 요청이 동적으로 우선 순위를 지정하는 앱 대기 버킷이 도입되었습니다.

    그래서 다음과 같은 사용용도에 따라 적합한 방법을 택하도록 안내하고 있습니다.               https://developer.android.com/images/guide/background/bg-job-choose.svg

    동작 오래걸리는 HTTP통신 다운로드는 다운로드 매니저, 지연 가능한 동작이라면 포그라운드 서비스, 시스템 상태에 따라 영향을 받는 작업은 워크 매니저, 정확한 시각에 동작해야한다면 알람 매니저를 쓰라고 권고하고 있습니다.

    그 중에서도 WorkManager는 앱이 종료되거나 장치가 다시 시작되더라도 실행될 것으로 예상되는 지연이 가능한 비동기 작업을 쉽게 예약할 수 있습니다. (안정적으로 실행가능)

    그래서 예약된 작업을 모니터링하고 관리할 수 있으며, Doze 모드와 같은 절전 기능을 준수합니다. 예를 들면 다음과 같은 작업에 사용하면 좋습니다.

    - 백엔드 서비스에 로그, 분석 보내기

   - 앱의 데이터를 서버와 주기적으로 동기화 할때 

   사용 예시는 다음과 같습니다.

[ Kotlin ]

//백그라운드 Task 만들기
class UploadWorker(appContext: Context, workerParams: WorkerParameters)
    : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        // Do the work here--in this case, upload the images.

        uploadImages()

        // Indicate whether the task finished successfully with the Result
        return Result.success()
    }
}

//실행
val uploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
        .build()
WorkManager.getInstance().enqueue(uploadWorkRequest)

 

[ Java ]

//백그라운드 Task 만들기
public class UploadWorker extends Worker {

    public UploadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
      // Do the work here--in this case, upload the images.

      uploadImages()

      // Indicate whether the task finished successfully with the Result
      return Result.success()
    }
}

//실행
OneTimeWorkRequest uploadWorkRequest = new OneTimeWorkRequest.Builder(UploadWorker.class)
        .build()
WorkManager.getInstance().enqueue(uploadWorkRequest);

 

위의 예제에서 doWork() 메소드가 WorkManager에서 제공하는 백그라운드 쓰레드에서 동기적으로 실행됩니다. 그래서 해당 메소드 안에서 위의 예제처럼 이미지를 업로드하려는 uploadImages()라는 메소드를 삽입하였습니다.

WorkManager를 통한 예제는 https://github.com/googlesamples/android-architecture-components/tree/master/WorkManagerSample 을 참고해주세요~

 

728x90