📊 Capítulo 17: WorkManager & Background Tasks
Especialização em Mobile Nativo Android
🗺️ A Garantia de Execução com Android Jetpack WorkManager
flowchart TD
APP["App agenda tarefa com Constraints (ex: Bateria > 20% & Conectado no Wi-Fi)"]
--> WM["WorkManager Engine (Persiste no SQLite interno do Android)"]
WM --> CHECK{"Condições do SO atendidas?"}
CHECK -- "SIM" --> EXEC["Executa CoroutineWorker.doWork() mesmo se o app for FECHADO pelo usuário!"]
CHECK -- "NÃO" --> WAIT["Aguardar até o smartphone conectar ao Wi-Fi ou carregar"]
EXEC --> RETRY{"Houve Falha de Rede?"}
RETRY -- "SIM" --> BACKOFF["Result.retry() com Exponential Backoff"]
RETRY -- "NÃO" --> SUCCESS["Result.success()"]
style APP fill:#ede7f6,stroke:#512da8,stroke-width:2px
style WM fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style CHECK fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style EXEC fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style WAIT fill:#ffebee,stroke:#d32f2f,stroke-width:1.5px
style RETRY fill:#fff3e0,stroke:#ff9800,stroke-width:1.5px
style BACKOFF fill:#fff9c4,stroke:#fbc02d,stroke-width:1.5px
style SUCCESS fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
🎯 Slide 1: Implementando um CoroutineWorker
class SincronizacaoWorker(
context: Context,
params: WorkerParameters,
private val repository: TransacaoRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
return try {
repository.sincronizarComServidor()
Result.success()
} catch (e: Exception) {
Result.retry()
}
}
}
🎯 Slide 2: Definindo Constraints Rígidas
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // Somente Wi-Fi
.setRequiresBatteryNotLow(true)
.build()
val syncRequest = PeriodicWorkRequestBuilder<SincronizacaoWorker>(6, TimeUnit.HOURS)
.setConstraints(constraints)
.build()
🎯 Slide 3: Execução Imediata com Expedited Work
- Para uploads prioritários enquanto o app vai para o background, utilize
setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)com notificações em primeiro plano (Foreground Service).
🔗 Navegação do Capítulo 17
| 📖 Ler Conteúdo Completo | 🧠 Fazer Quiz | 💻 Ver Exemplos | 🧩 Exercícios |
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim