Search code examples
androidsql-serveralarmmanagerbackground-service

How to fetch data from the database every day at 9 am in Android?


I'm creating an event app for Android. I am using a local database with the SQL Server and I have some questions about how to implement a background service that retrieves the most recent events from my database. Basically, I wanted something like this: every day, at 9 am, I get a notification that new events have been added. For that, I thought about using a background service and the alarm manager that every day at 9 am called the service that would look for recent events in my database. But I have some doubts on how I could do this? I saw some things on the internet but I ended up getting confused. And if there was no internet, was it possible to access the database as soon as there was a connection? Thanks to anyone who to help me.


Solution

  • What you are looking for is Workermanager. https://developer.android.com/topic/libraries/architecture/workmanager/basics Simplified: You define a function which is called when the constraints you set are met. these constraints are 9 am and internet available and repeat every 24h.

    I would use a PeriodicworkRequest for your task and set the time, when the first execution should be done with an initialdelay which you can define dynamic with some code, depending on the current time.

    You can as you wrote in a comment do the work with a OneTimeWork which also triggers another OneTimeWork. The Request is only executed when all constraints are met and is postponed until they are met.

    It is a matter of how time sensitive your case is, wether you use OneTimeWork or a PeriodicWork

    This article could help you find your preferred solution https://medium.com/androiddevelopers/workmanager-periodicity-ff35185ff006