WorkManager ha il supporto integrato per i worker a lunga esecuzione. In questi casi, WorkManager può fornire un segnale al sistema operativo che indica che il processo deve essere mantenuto attivo, se possibile, durante l'esecuzione di questo lavoro. Questi worker possono essere eseguiti per più di 10 minuti. Alcuni esempi di casi d'uso di questa nuova funzionalità sono i caricamenti o i download collettivi (che non possono essere suddivisi), l'elaborazione locale di un modello di ML o un'attività importante per l'utente dell'app.
Dietro le quinte, WorkManager gestisce ed esegue per tuo conto un servizio in primo piano per eseguire il WorkRequest
, mostrando al contempo una notifica configurabile.
ListenableWorker
ora supporta l'API setForegroundAsync()
e
CoroutineWorker
supporta un'API setForeground()
in sospensione. Queste API consentono agli sviluppatori di specificare che questo WorkRequest
è importante (dal punto di vista dell'utente) o a esecuzione prolungata.
A partire da 2.3.0-alpha03
, WorkManager consente anche di creare un
PendingIntent
, che può essere utilizzato per annullare i worker senza dover
registrare un nuovo componente Android utilizzando l'API createCancelPendingIntent()
. Questo approccio è particolarmente utile se utilizzato con le API setForegroundAsync()
o setForeground()
, che possono essere utilizzate per aggiungere un'azione di notifica per annullare il Worker
.
Creazione e gestione di worker a lungo termine
Dovrai utilizzare un approccio leggermente diverso a seconda che tu stia scrivendo codice in Kotlin o Java.
Kotlin
Gli sviluppatori Kotlin devono utilizzare CoroutineWorker
. Anziché utilizzare
setForegroundAsync()
, puoi utilizzare la versione in sospensione di questo metodo,
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
Gli sviluppatori che utilizzano un ListenableWorker
o un Worker
possono chiamare l'API setForegroundAsync()
, che restituisce un ListenableFuture<Void>
. Puoi anche chiamare setForegroundAsync()
per aggiornare un Notification
in corso.
Ecco un semplice esempio di un worker a lungo termine che scarica un file. Questo worker tiene traccia dell'avanzamento per aggiornare un Notification
in corso che mostra l'avanzamento del download.
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
}
}
Aggiungere un tipo di servizio in primo piano a un worker a lungo termine
Se la tua app ha come target Android 14 (livello API 34) o versioni successive, devi specificare un
tipo di servizio in primo piano per tutti i worker a lungo termine.
Se la tua app ha come target Android 10 (livello API 29) o versioni successive e contiene un worker a lungo termine che richiede l'accesso alla posizione, indica che il worker utilizza un tipo di servizio in primo piano location
.
Se la tua app ha come target Android 11 (livello API 30) o versioni successive
e contiene un worker a lungo termine che richiede l'accesso alla fotocamera o al microfono,
dichiara rispettivamente i tipi di servizio in primo piano camera
o microphone
.
Per aggiungere questi tipi di servizi in primo piano, completa i passaggi descritti nelle sezioni seguenti.
Dichiara i tipi di servizi in primo piano nel file manifest dell'app
Dichiara il tipo di servizio in primo piano del worker nel file manifest dell'app. Nel seguente esempio, il lavoratore richiede l'accesso alla posizione e al microfono:
AndroidManifest.xml
<service android:name="androidx.work.impl.foreground.SystemForegroundService" android:foregroundServiceType="location|microphone" tools:node="merge" />
Specificare i tipi di servizi in primo piano in fase di esecuzione
Quando chiami setForeground()
o setForegroundAsync()
, assicurati di specificare un
tipo di servizio in primo piano.
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); }