Unterstützung für langlebige Worker

WorkManager bietet integrierte Unterstützung für lang laufende Worker. In solchen Fällen kann WorkManager dem Betriebssystem signalisieren, dass der Prozess nach Möglichkeit während der Ausführung dieser Arbeit aktiv bleiben soll. Diese Worker können länger als 10 Minuten ausgeführt werden. Beispiele für Anwendungsfälle für diese neue Funktion sind Bulk-Uploads oder ‑Downloads (die nicht in Blöcke aufgeteilt werden können), die lokale Verarbeitung eines ML-Modells oder eine Aufgabe, die für den Nutzer der App wichtig ist.

Im Hintergrund verwaltet und führt WorkManager einen Dienst im Vordergrund aus, um die WorkRequest auszuführen. Außerdem wird eine konfigurierbare Benachrichtigung angezeigt.

ListenableWorker unterstützt jetzt die setForegroundAsync() API und CoroutineWorker unterstützt eine aussetzende setForeground() API. Mit diesen APIs können Entwickler angeben, dass dieses WorkRequest (aus Nutzersicht) wichtig oder langwierig ist.

Ab 2.3.0-alpha03 können Sie mit WorkManager auch einen PendingIntent erstellen, mit dem Worker abgebrochen werden können, ohne dass eine neue Android-Komponente mit der createCancelPendingIntent() API registriert werden muss. Dieser Ansatz ist besonders nützlich, wenn er mit den APIs setForegroundAsync() oder setForeground() verwendet wird, mit denen eine Benachrichtigungsaktion zum Abbrechen des Worker hinzugefügt werden kann.

Lang andauernde Worker erstellen und verwalten

Je nachdem, ob Sie in Kotlin oder Java programmieren, verwenden Sie einen etwas anderen Ansatz.

Kotlin

Kotlin-Entwickler sollten CoroutineWorker verwenden. Anstelle von setForegroundAsync() können Sie die aussetzende Version dieser Methode verwenden: 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

Entwickler, die ein ListenableWorker oder ein Worker verwenden, können die setForegroundAsync() API aufrufen, die ein ListenableFuture<Void> zurückgibt. Sie können auch setForegroundAsync() aufrufen, um eine laufende Notification zu aktualisieren.

Hier ist ein einfaches Beispiel für einen Worker mit langer Ausführungszeit, der eine Datei herunterlädt. Dieser Worker verfolgt den Fortschritt, um eine laufende Notification zu aktualisieren, die den Downloadfortschritt anzeigt.

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

Typ für Dienst im Vordergrund zu einem Worker mit langer Ausführungszeit hinzufügen

Wenn Ihre App auf Android 14 (API-Level 34) oder höher ausgerichtet ist, müssen Sie für alle lang laufenden Worker einen Diensttyp im Vordergrund angeben. Wenn Ihre App auf Android 10 (API-Level 29) oder höher ausgerichtet ist und einen langlebigen Worker enthält, der Zugriff auf den Standort benötigt, geben Sie an, dass der Worker einen Dienst im Vordergrundtyp von location verwendet.

Wenn Ihre App auf Android 11 (API-Level 30) oder höher ausgerichtet ist und einen langlebigen Worker enthält, der Zugriff auf die Kamera oder das Mikrofon benötigt, deklarieren Sie den Diensttyp im Vordergrund camera bzw. microphone.

Führen Sie die in den folgenden Abschnitten beschriebenen Schritte aus, um diese Typen von Diensten im Vordergrund hinzuzufügen.

Typen von Diensten im Vordergrund im App-Manifest deklarieren

Deklarieren Sie den Typ des Dienstes im Vordergrund des Workers im Manifest Ihrer App. Im folgenden Beispiel benötigt der Worker Zugriff auf den Standort und das Mikrofon:

AndroidManifest.xml

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

Typen von Diensten im Vordergrund zur Laufzeit angeben

Wenn Sie setForeground() oder setForegroundAsync() aufrufen, müssen Sie einen Typ des Dienstes im Vordergrund angeben.

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