Unterstützung für langlebige Worker

WorkManager verfügt über eine integrierte Unterstützung für langlebige Mitarbeiter. In solchen Fällen kann WorkManager dem Betriebssystem signalisieren, dass der Prozess während der Ausführung nach Möglichkeit aktiv gehalten werden sollte. 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 aufgeteilt werden können), die lokale Bearbeitung eines ML-Modells oder eine Aufgabe, die für den Nutzer der Anwendung wichtig ist.

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

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

Ab 2.3.0-alpha03 können Sie in WorkManager auch eine PendingIntent erstellen, mit der Mitarbeiter gestrichen werden können, ohne eine neue Android-Komponente mit der createCancelPendingIntent() API registrieren zu müssen. Dieser Ansatz ist besonders nützlich, wenn er mit der setForegroundAsync() oder setForeground() API verwendet wird, mit der eine Benachrichtigungsaktion zum Abbrechen von Worker hinzugefügt werden kann.

Worker mit langer Ausführungszeit erstellen und verwalten

Der Ansatz hängt davon ab, ob Sie in Kotlin oder Java programmieren.

Kotlin

Kotlin-Entwickler sollten CoroutineWorker verwenden. Anstelle von setForegroundAsync() können Sie die haltende 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 ListenableWorker oder 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 lang andauernden Worker, der eine Datei herunterlädt. Dieser Worker verfolgt den Fortschritt und aktualisiert einen laufenden Notification, der 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
   }
}

Einem Worker mit langer Ausführungszeit einen Diensttyp im Vordergrund hinzufügen

Wenn deine App auf Android 14 (API-Level 34) oder höher ausgerichtet ist, musst du für alle Worker mit langer Ausführungszeit einen Diensttyp im Vordergrund angeben. Wenn Ihre App auf Android 10 (API-Level 29) oder höher ausgerichtet ist und einen lang andauernden Worker enthält, der Zugriff auf den Standort benötigt, geben Sie an, dass der Worker den Diensttyp location im Vordergrund verwendet.

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

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 im Manifest Ihrer App den Diensttyp des Workers im Vordergrund. 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 während der Laufzeit angeben

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

MeinStandortundMikrofonmitarbeiter

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