Sync only while the app is open.
This commit is contained in:
1 parent
f2dac546d0
commit
ee1079a079
7 files changed
+3
-54
No files matched your search
@@ -1,17 +1,10 @@
|
||||
package com.racingapp.pitlog.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.time.LocalTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
@@ -23,10 +16,7 @@ import org.json.JSONObject
|
||||
|
||||
class SyncException(message: String) : Exception(message)
|
||||
|
||||
private const val WORK_NAME = "pitlog-sync"
|
||||
|
||||
class PitSync(
|
||||
private val appContext: Context,
|
||||
private val dao: RaceDao,
|
||||
private val preferences: SyncPreferences,
|
||||
) {
|
||||
@@ -39,30 +29,10 @@ class PitSync(
|
||||
|
||||
fun saveAddress(address: String) {
|
||||
preferences.address = address.trim().trimEnd('/')
|
||||
schedule()
|
||||
}
|
||||
|
||||
fun setAutomatic(enabled: Boolean) {
|
||||
preferences.automatic = enabled
|
||||
schedule()
|
||||
}
|
||||
|
||||
fun schedule() {
|
||||
try {
|
||||
val manager = WorkManager.getInstance(appContext)
|
||||
if (!preferences.automatic || preferences.address.isBlank()) {
|
||||
manager.cancelUniqueWork(WORK_NAME)
|
||||
return
|
||||
}
|
||||
val request = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
|
||||
.setConstraints(
|
||||
Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(),
|
||||
)
|
||||
.build()
|
||||
manager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
|
||||
} catch (_: Exception) {
|
||||
// Unit tests do not start WorkManager.
|
||||
}
|
||||
}
|
||||
|
||||
fun launchAutomatic() {
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.racingapp.pitlog.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.racingapp.pitlog.RacingApp
|
||||
|
||||
class SyncWorker(
|
||||
context: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(context, params) {
|
||||
override suspend fun doWork(): Result {
|
||||
val app = applicationContext as? RacingApp ?: return Result.success()
|
||||
app.repository.syncAutomatic()
|
||||
return Result.success()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user