Search code examples
androidkotlinservice

Auto call function after some time with service


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

Edit 1:

    fun autoConsumingSendingToken() {
        Log.d("tokenworker", "5 AUTOCONSUMING MAINACTIVITY")
        val myWorkRequest: WorkRequest =
            PeriodicWorkRequestBuilder<AutoTokenWorker>(20, TimeUnit.SECONDS).build()

        WorkManager
            .getInstance(applicationContext)
            .enqueue(myWorkRequest)
    }

Solution

  • 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.