The application requires periodic (15-30 mins) data synchronization with the backend.
I implemented this using the WorkManager API, but I encountered the issue that synchronization only triggers when the application is running; if the user or the Android OS terminates the application, my sync worker stops working.
At the same time, I see that synchronization works on the emulator even if I terminate the process.
I have read a lot of information on this topic but cannot see any mistake on my end.
Could you please advise what might be the problem?
My test worker (writes logs in file):
class TestWorker
(appContext: Context, params: WorkerParameters) :
CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
Timber.d("Message from worker")
return Result.success()
}
}
My Application (starts sync worker):
@HiltAndroidApp
@Singleton
class WorkTestApp : Application() {
override fun onCreate() {
super.onCreate()
val fileLogger = FileLogger(context = this)
val reportingTree = ReportingTree(fileLogger)
Timber.plant(reportingTree)
val periodicWorkRequest = PeriodicWorkRequestBuilder<TestWorker>(
repeatInterval = 15,
repeatIntervalTimeUnit = TimeUnit.MINUTES
).build()
val workManager = WorkManager.getInstance(this)
workManager.enqueueUniquePeriodicWork(
"SYNC_WORK_NAME",
ExistingPeriodicWorkPolicy.KEEP,
periodicWorkRequest
)
}
}
App manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:name=".WorkTestApp"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WorkerTest"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.WorkerTest">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>