0

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)
    }
chrisu.chrisu
  • 119
  • 2
  • 14

1 Answers1

1

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.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58
  • I put it in my MainActivity but it launch only once with launching the application. Check edit for code. Should I put it in somekind of service? What do you think? And.. also I made coroutineworker instead of just worker. – chrisu.chrisu Jan 26 '22 at 11:30
  • You have set your periodic work to 20 seconds which is not supported by WorkManager (minimum recurring period is 15 minutes). If you must use this period you need to either use a foreground service or use this trick https://stackoverflow.com/a/70134556/3016293 which is not recommended as it will make your app very battery consuming. – hiddeneyes02 Jan 26 '22 at 13:37
  • I need 24 hours but I just wanted to test it. Thanks for info! – chrisu.chrisu Jan 26 '22 at 14:24