A.Ali
A.Ali

Reputation: 13

How to fetch data from API within background service in android kotlin?

I want to fetch some data from my own Api but I want the app to fetch this data within background service in order to save it into my database and this should be done every specific time according to my choice. Any help with this and I will appreciate that. Thanks for you all.

Upvotes: 0

Views: 2074

Answers (1)

Circusmagnus
Circusmagnus

Reputation: 66

Instead of background service use WorkManager: https://developer.android.com/topic/libraries/architecture/workmanager

It lets you schedule background tasks at specific intervals, on specific network connectivity (e.g. wifi only) etc. Powerful stuff.

Sample usage (copied from linked page), when you wish to perform some work at hourly interval while device is charging:

val constraints = Constraints.Builder()
        .setRequiresCharging(true)
        .build()

val saveRequest =
PeriodicWorkRequestBuilder<SaveImageToFileWorker>(1, TimeUnit.HOURS)
    .setConstraints(constraints)
    .build()

WorkManager.getInstance(myContext)
    .enqueue(saveRequest)

Upvotes: 2

Related Questions