Issue
I'm writing an app with Xamarin.Android to retrieve data from some domotic sensors(Sonoff, Shelly) and to set some switches. I need it to make api calls even in background, say about every 5 or 10 minutes. I know it's a very short amount of time, I plan to do this with an Arduino later, but now I need this. I researched a bit, read about Services and their limitations, but I can't figure out how to do this. Can someone help me? Thanks
Solution
You can either:
- create a Foreground Service that keeps running, and you execute a timer there
- use WorkManager from Android X, which depending on device capabilities and software versions will use the following in priority:
- JobScheduler
- Firebase JobDispatcher
- AlarmManager
JobScheduler allows you (kind of like cron on Linux) to set up scheduled tasks to be run. However, it is limited in how frequent you can do this. This frequency depends on Android version and depends on the criteria on the job and whether the device is not running out of resources.
With the foreground service, you can do more or less what you want as long as the service is alive. You might need to disable battery optimizations in battery settings for your App, but otherwise it should just work.
Apart from these features, unless you are either using a rooted device or you are device admin on the device, you can't do much more. In case of root/device admin, you can mark your app as Persistent
to disallow it being killed by Android.
Answered By - Cheesebaron