장기 실행 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를 취소할 수 있습니다. 이 접근법은 setForeground() API와 함께 사용할 때 특히 유용하며, Worker를 취소하기 위해 알림 작업을 추가하는 데 사용할 수 있습니다.

장기 실행 작업자 생성 및 관리

CoroutineWorker 및 정지 setForeground() 메서드를 사용하여 장기 실행 작업자를 구성하고 진행 중인 Notification를 업데이트합니다.

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"
    }
}

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

앱이 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

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