开发者

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

开发者 https://www.devze.com 2023-03-06 17:52 出处:网络
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.

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开发者_StackOverflow社区 class to schedule future polls

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

Thanks!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消