android6-3 Exercise 1: Periodic sync ================================= dependencies { implementation("androidx.work:work-runtime-ktx:") // check the current artifact and version androidTestImplementation("androidx.work:work-testing:") } import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters class SyncNotesWorker( appContext: Context, params: WorkerParameters ) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result { // Manual DI (Architecture & Data 9): the worker reaches the container through the Application val repository = (applicationContext as NotesApplication).container.notesRepository return when (repository.refresh()) { is RefreshResult.Success -> Result.success() is RefreshResult.NoConnection -> Result.retry() // try again later, with backoff else -> Result.failure() } } } import androidx.work.* import java.util.concurrent.TimeUnit fun scheduleNotesSync(context: Context) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresBatteryNotLow(true) .build() val request = PeriodicWorkRequestBuilder(1, TimeUnit.HOURS) .setConstraints(constraints) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build() // One named job: calling this again must not create a second one WorkManager.getInstance(context).enqueueUniquePeriodicWork( "notes-sync", ExistingPeriodicWorkPolicy.KEEP, request ) } // In NotesApplication.onCreate(): scheduleNotesSync(this) Inspect: Android Studio, View > Tool Windows > App Inspection, Background Task Inspector (general knowledge; name and location may differ in your version). Expected: a periodic work item "notes-sync" ENQUEUED, waiting for a connected network and a battery that is not low, running when those hold. Shortest interval: periodic work has a 15 minute minimum (general knowledge, not checked in the searches). Try 1 minute and report what you see; do not assume the result. Code unrun.