WorkManager には、長時間実行ワーカーに関する組み込みのサポートが追加されています。これにより、このワーカーが実行されている間は可能な限りプロセスを維持するよう WorkManager から OS に通知できます。これらのワーカーは、10 分以上実行できます。この新機能のユースケースの例には、一括アップロードまたはダウンロード(非チャンク型のみ)、ML モデルのローカル処理、アプリユーザーにとって重要なタスクなどが含まれます。
内部的には、WorkManager がフォアグラウンド サービスを管理、実行して WorkRequest を実行し、同時に設定可能な通知を表示します。
現在、ListenableWorker は setForegroundAsync() API をサポートしており、CoroutineWorker は、サスペンドする setForeground() API をサポートしています。デベロッパーはこれらの API を使用して、WorkRequest が重要なタスクか(ユーザーの観点から)、長時間実行ワーカーかを指定できます。
2.3.0-alpha03 以降の WorkManager では、PendingIntent の作成も可能になりました。createCancelPendingIntent() API を使用すれば、新しい Android コンポーネントを登録せずにワーカーをキャンセルできます。これを 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)以降をターゲットとするアプリでは、すべての長時間実行ワーカーにフォアグラウンド サービス タイプを指定する必要があります。アプリが Android 10(API レベル 29)以降をターゲットとしており、位置情報へのアクセスを必要とする長時間実行ワーカーが含まれている場合は、そのワーカーがフォアグラウンド サービス タイプ location を使用することを示します。
アプリが Android 11(API レベル 30)以降をターゲットとし、カメラまたはマイクへのアクセスを必要とする長時間実行ワーカーが含まれている場合は、camera または microphone のフォアグラウンド サービス タイプをそれぞれ宣言します。
これらのフォアグラウンド サービス タイプを追加するには、以下のセクションで説明する手順を実行します。
アプリ マニフェストでフォアグラウンド サービス タイプを宣言する
アプリのマニフェストで、ワーカーのフォアグラウンド サービス タイプを宣言します。次の例では、ワーカーは位置情報とマイクへのアクセスを必要とします。
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 ) }