Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to have an Android app poll periodically in the background

Tags:

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:

  • Bind once, and have the service run in an infinite loop, sleeping for 10 minutes between each loop
  • Bind and unbind right when it's done, scheduling the next bind somehow in 10 minutes
  • Using the AlarmManager class to schedule future polls

What are the trade offs? How does the Gmail app accomplish it?

Thanks!

like image 617
Brian Armstrong Avatar asked May 19 '11 00:05

Brian Armstrong


People also ask

What is the current recommended way to handle long running background tasks?

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.

How do I make my Android app always running?

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.


2 Answers

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)

like image 130
aromero Avatar answered Sep 20 '22 14:09

aromero


  • 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.

like image 27
Aleadam Avatar answered Sep 23 '22 14:09

Aleadam