WorkManager offre 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 dell'operazione. Questi worker possono essere eseguiti per più di 10 minuti. Esempi di casi d'uso di questa nuova funzionalità includono caricamenti collettivi o download (che non possono essere suddivisi in blocchi), analisi su un modello ML a livello locale o un'attività importante per l'utente dell'app.
In background, WorkManager gestisce ed esegue per tuo conto un servizio in primo piano al fine di eseguire WorkRequest
, mostrando al contempo una notifica configurabile.
ListenableWorker
ora supporta l'API setForegroundAsync()
e
CoroutineWorker
supporta un'API setForeground()
sospesa. Queste API consentono agli sviluppatori di specificare che questo WorkRequest
è importante (dal punto di vista dell'utente) o di lunga durata.
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 Worker
.
Creazione e gestione dei worker di lunga durata
Utilizzerai un approccio leggermente diverso a seconda che tu stia codificando in Kotlin o Java.
Kotlin
Gli sviluppatori Kotlin devono utilizzare CoroutineWorker
. Anziché utilizzare setForegroundAsync()
, puoi utilizzare la versione sospesa di quel 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 ListenableWorker
o Worker
possono chiamare
l'API setForegroundAsync()
, che restituisce ListenableFuture<Void>
. Puoi
anche chiamare il numero setForegroundAsync()
per aggiornare un Notification
in corso.
Ecco un semplice esempio di un worker a lunga esecuzione 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
}
}
Aggiungi un tipo di servizio in primo piano a un worker di lunga durata
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 di lunga durata.
Se la tua app ha come target Android 10 (livello API 29) o versioni successive e contiene un lavoratore a lunga esecuzione 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 di lunga data 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.
Dichiarare 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. Nell'esempio seguente, il worker richiede l'accesso alla posizione e al microfono:
<service android:name="androidx.work.impl.foreground.SystemForegroundService" android:foregroundServiceType="location|microphone" tools:node="merge" />
Specifica i tipi di servizi in primo piano in fase di runtime
Quando chiami setForeground()
o setForegroundAsync()
, assicurati di specificare un
tipo di servizio in primo piano.
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); }