Compatibilité avec les workers de longue durée

WorkManager est compatible avec les workers de longue durée. Dans ce cas, WorkManager peut fournir au système d'exploitation un signal indiquant que le processus doit être maintenu actif si possible pendant l'exécution de cette tâche. Ces nœuds de calcul peuvent s'exécuter pendant plus de 10 minutes. Voici quelques exemples de cas d'utilisation de cette nouvelle fonctionnalité : importations ou téléchargements groupés (qui ne peuvent pas être fragmentés), traitement en local d'un modèle de ML ou tâche importante pour l'utilisateur de l'application.

En arrière-plan, WorkManager gère et exécute un service de premier plan en votre nom pour exécuter WorkRequest, tout en affichant une notification configurable.

ListenableWorker accepte à présent l'API setForegroundAsync() et CoroutineWorker permet la suspension d'une API setForeground(). Ces API permettent aux développeurs de préciser que ce WorkRequest est important (du point de vue de l'utilisateur) ou de longue durée.

À partir de la version 2.3.0-alpha03, WorkManager vous permet également de créer un PendingIntent, qui peut être utilisé pour annuler des nœuds de calcul sans avoir à enregistrer un nouveau composant Android à l'aide de createCancelPendingIntent(). Cette approche est particulièrement utile lorsqu'elle est utilisée avec les API setForegroundAsync() ou setForeground(), qui permettent d'ajouter une action de notification pour annuler le Worker.

Créer et gérer des nœuds de calcul de longue durée

Vous allez adopter une approche légèrement différente selon que vous codez en langage Kotlin ou Java.

Kotlin

Les développeurs Kotlin doivent utiliser CoroutineWorker. Au lieu d'utiliser setForegroundAsync(), vous pouvez utiliser la version de suspension de cette méthode, 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

Les développeurs qui utilisent ListenableWorker ou Worker peuvent appeler l'API setForegroundAsync(), qui renvoie un ListenableFuture<Void>. Vous pouvez également appeler setForegroundAsync() pour mettre à jour une Notification en cours.

Voici un exemple simple de nœud de calcul de longue durée qui télécharge un fichier. Ce nœud de calcul suit la progression de la mise à jour d'un Notification en cours qui affiche la progression du téléchargement.

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

Ajouter un type de service de premier plan à un nœud de calcul de longue durée

Si votre application cible Android 14 (niveau d'API 34) ou une version ultérieure, vous devez spécifier un type de service de premier plan pour tous les nœuds de calcul de longue durée. Si votre application cible Android 10 (niveau d'API 29) ou une version ultérieure et contient un nœud de calcul de longue durée nécessitant un accès à la localisation, indiquez qu'il utilise un type de service de premier plan de location.

Si votre application cible Android 11 (niveau d'API 30) ou une version ultérieure et contient un nœud de calcul de longue durée nécessitant un accès à l'appareil photo ou au micro, déclarez respectivement les types de services de premier plan camera ou microphone.

Pour ajouter ces types de services de premier plan, suivez les étapes décrites dans les sections suivantes.

Déclarer les types de services de premier plan dans le fichier manifeste de l'application

Déclarez le type de service de premier plan du nœud de calcul dans le fichier manifeste de votre application. Dans l'exemple suivant, le nœud de calcul a besoin d'accéder à la position et au micro :

AndroidManifest.xml

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

Préciser les types de services de premier plan lors de l'exécution

Lorsque vous appelez setForeground() ou setForegroundAsync(), veillez à spécifier un type de service de premier plan.

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);
}