Home > Back-end >  Auto call function after some time with service
Auto call function after some time with service

Time:01-26

I would like to call a function with a api method to @Post some information like registered token from notifications (FCM). When application will be killed it also should be triggered. What is the best way to achieve this feature and could I use somehow notification service to make it or should I make another service like in this example below.

Android: keep Service running when app is killed

CodePudding user response:

Your best approach to this kind of situation is to use Android WorkManager.

Essentially, you have to declare a class containing the work you want to do:


class MyWorker(appContext: Context, workerParams: WorkerParameters):
       Worker(appContext, workerParams) {

   override fun doWork(): Result {
       //call your function
       return Result.success()
   }
}

Then create and schedule your work:

val myWorkRequest: WorkRequest =
   PeriodicWorkRequestBuilder<MyWorker>(1, TimeUnit.HOURS).build()

WorkManager
    .getInstance(myContext)
    .enqueue(myWorkRequest)

You can tweak work schedule according to your needs.

  •  Tags:  
  • Related