What I want to implement is a background service that fetch data from the server every hour. I expect this service can run periodically after the boot. Thus, I choose to use JobScheduler to implement this function.
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val builder = JobInfo.Builder(1, ComponentName(this, PullDataJob::class.java))
.setPeriodic(1000L * 60 * 60) // one hour
.setRequiredNetworkType(NETWORK_TYPE_ANY)
.setPersisted(true)
jobScheduler.schedule(builder.build())
This is my currently code, which is placed inside onCreate(). However, I find that if I put the JobScheduler.schedule() in onCreate(), the service will be automatically executed every time I open the application.
Where is the best place to put the code above to make the service run periodically even if the user never opens the application after system boot?