Take the Gmail app as an example. Whether the phone is on or not, it polls every 10 minutes or so to download new emails which may have arrived since you last checked.
I know how to create a new service and bind to it. But I can see a few ways to accomplish this:
What are the trade offs? How does the Gmail app accomplish it?
Thanks!
Recommended solutionScheduling deferred work through WorkManager is the best way to handle tasks that don't need to run immediately but which ought to remain scheduled when the app closes or the device restarts.
You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.
Gmail app uses pushing, not polling. I suggest using this technique instead, polling is a battery killer in mobile devices.
To implement pushing, take a look at C2DM.
If you still want to poll, the recommended way would be to set up a periodic alarm in the AlarmManager.
UPDATE: Google has deprecated C2DM and replaced it with Google Cloud Messaging (GCM)
UPDATE: Google has deprecated GCM and replaced it with Firebase Cloud Messaging (FCM)
For a continuous, but not intensive poll like the one you comment (in the range of minutes between polls), I would implement it with AlarmManager. That way you make sure the phone wakes up to poll without the need for a wakelock, which would destroy your battery. As CommonsWare pointed out, you will still need to implement a wakelock for the time your code is executing, but you can release it as soon as the code is done, avoiding keeping the phone on while just waiting. See his comment for an example on how to implement it.
I would use a Service if, instead, you need faster polls during a shorter period of time (seconds between each poll), since setting alarms does not make sense to such short periods, and the battery would drain anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With