장기 실행 worker 지원

WorkManager에는 장기 실행 worker를 위한 지원이 내장되어 있습니다. 이러한 경우 WorkManager는 작업이 실행되는 동안 가능하면 프로세스를 활성 상태로 유지해야 한다는 신호를 OS에 제공할 수 있으며 장기 실행 worker는 10분 넘게 실행될 수 있습니다. 이 새로운 기능의 사용 사례로는 일괄 업로드 또는 일괄 다운로드(청크 불가), ML 모델의 로컬 크런칭, 앱 사용자에게 중요한 작업 등이 있습니다.

내부적으로 WorkManager는 개발자를 대신해서 포그라운드 서비스를 관리하고 실행하여 WorkRequest를 실행하며 구성 가능한 알림도 표시합니다.

ListenableWorker는 이제 setForegroundAsync() API를 지원하고 CoroutineWorker는 정지 API인 setForeground() API를 지원합니다. 이러한 API를 통해 개발자는 WorkRequest중요하다고 지정하거나(사용자 관점에서) 장기 실행 중이라고 지정할 수 있습니다.

또한 2.3.0-alpha03부터 WorkManager를 사용하면 PendingIntent를 만들 수 있으며 이를 통해 createCancelPendingIntent() API를 사용하여 새 Android 구성요소를 등록하지 않고도 worker를 취소할 수 있습니다. 이 접근법은 setForegroundAsync() 또는 setForeground() API와 함께 사용할 때 특히 유용하며, Worker를 취소하기 위해 알림 작업을 추가하는 데 사용할 수 있습니다.

장기 실행 worker 생성 및 관리

Kotlin으로 코딩하는지 또는 자바로 코딩하는지에 따라 약간 다른 접근법을 사용합니다.

Kotlin

Kotlin 개발자는 CoroutineWorker를 사용해야 합니다. setForegroundAsync()를 사용하는 대신 이 메서드의 정지 버전인 setForeground()를 사용하면 됩니다.

class DownloadWorker(context: Context, parameters: WorkerParameters) :
   CoroutineWorker(context, parameters) {

   private val notificationManager =
       context.getSystemService(Context.NOTIFICATION_SERVICE) as
               NotificationManager

   override suspend fun doWork(): Result {
       val inputUrl = inputData.getString(KEY_INPUT_URL)
                      ?: return Result.failure()
       val outputFile = inputData.getString(KEY_OUTPUT_FILE_NAME)
                      ?: return Result.failure()
       // Mark the Worker as important
       val progress = "Starting Download"
       setForeground(createForegroundInfo(progress))
       download(inputUrl, outputFile)
       return Result.success()
   }

   private fun download(inputUrl: String, outputFile: String) {
       // Downloads a file and updates bytes read
       // Calls setForeground() periodically when it needs to update
       // the ongoing Notification
   }
   // Creates an instance of ForegroundInfo which can be used to update the
   // ongoing notification.
   private fun createForegroundInfo(progress: String): ForegroundInfo {
       val id = applicationContext.getString(R.string.notification_channel_id)
       val title = applicationContext.getString(R.string.notification_title)
       val cancel = applicationContext.getString(R.string.cancel_download)
       // This PendingIntent can be used to cancel the worker
       val intent = WorkManager.getInstance(applicationContext)
               .createCancelPendingIntent(getId())

       // Create a Notification channel if necessary
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           createChannel()
       }

       val notification = NotificationCompat.Builder(applicationContext, id)
           .setContentTitle(title)
           .setTicker(title)
           .setContentText(progress)
           .setSmallIcon(R.drawable.ic_work_notification)
           .setOngoing(true)
           // Add the cancel action to the notification which can
           // be used to cancel the worker
           .addAction(android.R.drawable.ic_delete, cancel, intent)
           .build()

       return ForegroundInfo(notificationId, notification)
   }

   @RequiresApi(Build.VERSION_CODES.O)
   private fun createChannel() {
       // Create a Notification channel
   }

   companion object {
       const val KEY_INPUT_URL = "KEY_INPUT_URL"
       const val KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME"
   }
}

Java

ListenableWorker 또는 Worker를 사용하는 개발자는 ListenableFuture<Void>를 반환하는 setForegroundAsync() API를 호출할 수 있습니다. 또한, 진행 중인 Notification을 업데이트하기 위해 setForegroundAsync()를 호출할 수도 있습니다.

다음은 파일을 다운로드하는 장기 실행 worker의 간단한 예입니다. 이 worker는 진행률을 추적하여 다운로드 진행률을 보여주는 진행 중인 Notification을 업데이트합니다.

public class DownloadWorker extends Worker {
   private static final String KEY_INPUT_URL = "KEY_INPUT_URL";
   private static final String KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME";

   private NotificationManager notificationManager;

   public DownloadWorker(
       @NonNull Context context,
       @NonNull WorkerParameters parameters) {
           super(context, parameters);
           notificationManager = (NotificationManager)
               context.getSystemService(NOTIFICATION_SERVICE);
   }

   @NonNull
   @Override
   public Result doWork() {
       Data inputData = getInputData();
       String inputUrl = inputData.getString(KEY_INPUT_URL);
       String outputFile = inputData.getString(KEY_OUTPUT_FILE_NAME);
       // Mark the Worker as important
       String progress = "Starting Download";
       setForegroundAsync(createForegroundInfo(progress));
       download(inputUrl, outputFile);
       return Result.success();
   }

   private void download(String inputUrl, String outputFile) {
       // Downloads a file and updates bytes read
       // Calls setForegroundAsync(createForegroundInfo(myProgress))
       // periodically when it needs to update the ongoing Notification.
   }

   @NonNull
   private ForegroundInfo createForegroundInfo(@NonNull String progress) {
       // Build a notification using bytesRead and contentLength

       Context context = getApplicationContext();
       String id = context.getString(R.string.notification_channel_id);
       String title = context.getString(R.string.notification_title);
       String cancel = context.getString(R.string.cancel_download);
       // This PendingIntent can be used to cancel the worker
       PendingIntent intent = WorkManager.getInstance(context)
               .createCancelPendingIntent(getId());

       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           createChannel();
       }

       Notification notification = new NotificationCompat.Builder(context, id)
               .setContentTitle(title)
               .setTicker(title)
               .setSmallIcon(R.drawable.ic_work_notification)
               .setOngoing(true)
               // Add the cancel action to the notification which can
               // be used to cancel the worker
               .addAction(android.R.drawable.ic_delete, cancel, intent)
               .build();

       return new ForegroundInfo(notificationId, notification);
   }

   @RequiresApi(Build.VERSION_CODES.O)
   private void createChannel() {
       // Create a Notification channel
   }
}

장기 실행 worker에 포그라운드 서비스 유형 추가

앱이 Android 14 (API 수준 34) 이상을 타겟팅하는 경우 모든 장기 실행 worker에 포그라운드 서비스 유형을 지정해야 합니다. 앱에서 Android 10 (API 수준 29) 이상을 타겟팅하고 위치에 액세스해야 하는 장기 실행 worker를 포함하는 경우 worker가 포그라운드 서비스 유형 location를 사용한다는 점을 나타내세요.

앱이 Android 11 (API 수준 30) 이상을 타겟팅하고 카메라 또는 마이크에 액세스해야 하는 장기 실행 worker를 포함하는 경우 camera 또는 microphone 포그라운드 서비스 유형을 각각 선언하세요.

이러한 포그라운드 서비스 유형을 추가하려면 다음 섹션에 설명된 단계를 완료하세요.

앱 매니페스트에서 포그라운드 서비스 유형 선언

앱 매니페스트에서 worker의 포그라운드 서비스 유형을 선언하세요. 다음 예에서 worker는 위치 및 마이크에 액세스해야 합니다.

AndroidManifest.xml

<service
   android:name="androidx.work.impl.foreground.SystemForegroundService"
   android:foregroundServiceType="location|microphone"
   tools:node="merge" />

런타임 시 포그라운드 서비스 유형 지정

setForeground() 또는 setForegroundAsync()를 호출할 때는 포그라운드 서비스 유형을 지정해야 합니다.

MyLocationAndMicrophoneWorker

Kotlin

private fun createForegroundInfo(progress: String): ForegroundInfo {
   // ...
   return ForegroundInfo(NOTIFICATION_ID, notification,
           FOREGROUND_SERVICE_TYPE_LOCATION or
FOREGROUND_SERVICE_TYPE_MICROPHONE) }

Java

@NonNull
private ForegroundInfo createForegroundInfo(@NonNull String progress) {
   // Build a notification...
   Notification notification = ...;
   return new ForegroundInfo(NOTIFICATION_ID, notification,
           FOREGROUND_SERVICE_TYPE_LOCATION | FOREGROUND_SERVICE_TYPE_MICROPHONE);
}