# 11. Background Sync & WorkManager Optimization meta: id: android-production-11 feature: android-production priority: P2 depends_on: [] tags: [performance, background, production] objective: - Optimize background sync using WorkManager to keep data fresh without excessive battery drain deliverables: - WorkManager periodic sync workers - Battery-efficient sync strategy - Constraint-based scheduling - Sync status indicators steps: 1. Audit existing sync: - Review android/app/.../data/sync/SyncManager.kt - Review OfflineWorker.kt - Identify sync frequency and triggers 2. Optimize sync workers: - Use PeriodicWorkRequest for regular sync (15 min minimum) - Use OneTimeWorkRequest for immediate sync - Set constraints: requires network, battery not low - Use expedited work for urgent syncs 3. Implement battery-efficient sync: - Batch network requests - Use delta sync (only changed data) - Respect doze mode and app standby - Use JobScheduler for API 21-22 (WorkManager uses internally) 4. Add sync types: - Alert sync: high priority, frequent - Exposure sync: medium priority - Spam database update: low priority, daily - Watchlist sync: on change 5. Add user controls: - Settings toggle for background sync - Sync frequency preference (if applicable) - Manual sync button in settings - Last sync timestamp display 6. Handle failures: - Exponential backoff for failed syncs - Max retry limit - Alert user after repeated failures - Queue syncs for when online 7. Add tests: - Test worker execution - Test constraint handling - Test battery impact tests: - Unit: Test worker logic - Integration: Test WorkManager scheduling - Battery: Verify minimal battery impact acceptance_criteria: - WorkManager configured for periodic sync - Sync constraints: network available, battery not low - Delta sync reducing data transfer - Background sync respects doze mode - User can enable/disable background sync - Manual sync button in settings - Last sync timestamp visible - Failed syncs retry with exponential backoff - Battery impact <5% per day from background sync - Unit tests for all worker classes validation: - Enable background sync → workers scheduled - Turn on airplane mode → sync deferred - Disable battery saver → sync resumes - Check battery settings → Kordant background usage minimal - Trigger manual sync → data updates immediately notes: - WorkManager is already included (libs.work.runtime.ktx) - Minimum periodic work interval is 15 minutes - Android 12+ has stricter background restrictions - Use Foreground Service for urgent syncs if needed