Unterstützung für langlebige Worker

WorkManager bietet integrierte Unterstützung für Worker mit langer Laufzeit. In solchen Fällen kann WorkManager dem Betriebssystem signalisieren, dass der Prozess nach Möglichkeit aktiv bleiben soll, während diese Aufgabe ausgeführt wird. 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 in Ihrem Namen einen Dienst im Vordergrund aus , um die WorkRequest auszuführen. Gleichzeitig 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 diese WorkRequest aus Nutzersicht wichtig oder langwierig ist.

Ab 2.3.0-alpha03 können Sie mit WorkManager auch ein PendingIntent erstellen, mit dem Worker abgebrochen werden können, ohne dass mit der createCancelPendingIntent() API eine neue Android-Komponente registriert werden muss. Dieser Ansatz ist besonders nützlich in Kombination mit den APIs setForegroundAsync() oder setForeground(), mit denen eine Benachrichtigungsaktion hinzugefügt werden kann, um den Worker abzubrechen.

Worker mit langer Laufzeit 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, setForeground() verwenden.

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 einen ListenableWorker oder einen 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 Laufzeit, der eine Datei herunterlädt. Dieser Worker verfolgt den Fortschritt, um eine laufende Notification zu aktualisieren, in der der Downloadfortschritt angezeigt wird.

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

Dienst im Vordergrund zu einem Worker mit langer Laufzeit hinzufügen

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

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

Führen Sie die Schritte in den folgenden Abschnitten aus, um diese Dienste im Vordergrund hinzuzufügen.

Dienste im Vordergrund im App-Manifest deklarieren

Deklarieren Sie den Dienst 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" />

Dienste im Vordergrund zur Laufzeit angeben

Wenn Sie setForeground() oder setForegroundAsync() aufrufen, geben Sie einen Dienst im Vordergrund an.

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