WorkManager bietet integrierte Unterstützung für Worker mit langer Laufzeit. In solchen Fällen kann WorkManager dem Betriebssystem ein Signal senden, dass der Prozess nach Möglichkeit während der Ausführung dieser Aufgabe 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 das Hoch- oder Herunterladen von Dateien (die nicht in Chunks 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 in Ihrem Namen 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 setForeground()
API zum Sperren. Mit diesen APIs können Entwickler angeben, dass diese WorkRequest
aus Nutzersicht wichtig oder lang andauernd ist.
Ab 2.3.0-alpha03
können Sie mit WorkManager auch einen PendingIntent
erstellen, mit dem Sie Worker abbrechen können, ohne eine neue Android-Komponente mit der createCancelPendingIntent()
API registrieren zu müssen. Diese Vorgehensweise ist besonders nützlich in Verbindung mit den APIs setForegroundAsync()
oder setForeground()
, 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, müssen Sie etwas anders vorgehen.
Kotlin
Kotlin-Entwickler sollten CoroutineWorker
verwenden. Anstelle von setForegroundAsync()
können Sie die Version dieser Methode zum Sperren 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 ListenableWorker
oder Worker
verwenden, können die setForegroundAsync()
API aufrufen, die ListenableFuture<Void>
zurückgibt. Sie können auch setForegroundAsync()
aufrufen, um ein laufendes 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
}
}
Lang andauerndem Worker einen Diensttyp im Vordergrund hinzufügen
Wenn Ihre App auf Android 14 (API‑Level 34) oder höher ausgerichtet ist, müssen Sie für alle lang andauernden Worker einen Typ für Dienste im Vordergrund angeben.
Wenn Ihre App auf Android 10 (API-Level 29) oder höher ausgerichtet ist und einen Worker mit langer Ausführungszeit enthält, der Zugriff auf den Standort erfordert, geben Sie an, dass der Worker den Vordergrunddiensttyp 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 Vordergrunddiensttypen camera
bzw. microphone
.
Führen Sie die Schritte in den folgenden Abschnitten aus, um diese Arten 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 Diensttyp 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); }