Android Background Service vs AlarmManager

2019-05-01 04:39发布

问题:

Can someone give a little bit briefing or perhaps more elaborate details on differences Android background service with Alarm Manager?

How they differ? And in which situation I should use each?

I am developing an application that need to download data from Web Service at periodic time. The application has few modules and each modules has different interval time period to download / sync the data to Web Service.

Let say + Module A need to sync in every 15 mins + Module B need to sync in every 1 hour + Module C need to sync in every day + Module D need to sync weekly + Module E need to sync monthly

Which approach is better? And why?

Regards

回答1:

Alarm manager schedule the intents. Your service could be crashed and can be remove if memory is not available. But if you schedule Alarm you can invoke your specific service at the time of Alarm time. In your context Alarm is the more best option than running service.

Hope it will help you.



回答2:

With the help of the AlarmManager you can schedule intents. Your service or a BroadcastReceiver can listen to these scheduled intents and perform tasks at the given time. You can not only use the AlarmManager to implement program logic.

You can use the AlarmManager to dispatch an Intent every 15 minutes with an action for A, one every hour for B and so on. Either your modules are implement as independent services or you decide on the intent action what to do.

Please keep also in mind that long operations should not be performed in a BroadcastReceiver.



回答3:

There's a very good analysis on this new blog post: https://android-developers.googleblog.com/2018/10/modern-background-execution-in-android.html?linkId=58286424

For sync on regular basis you might end up using WorkManager, started on specific time or when triggered by a push message (FCM)