Surjya Narayana Padhi
Surjya Narayana Padhi

Reputation: 7841

Which one to choose for background task - a timer with repeated task or service with loop?

I have a repeated task(Task A) to do when I receive a broadcast in my application. I need to know which one is better between these options to do the repeated task?

  1. A Timer in a standalone class and does the Task A repeatedly on timer expiry?
  2. An android background service doing the Task A.

what are the pros and cons in choosing the above methods?

Upvotes: 1

Views: 364

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007554

what are the pros and cons in choosing the above methods?

You seem to assume that all possible "Task A" implementations are created equal. You also seem to assume that all periods (one millisecond to one century) are created equal. Neither of these are true.

It is impossible to answer your question in the abstract, and it would take a few dozen pages to explain all the possibilities.

My task need to update the location to my java class variable which is not an activity and has to update to a webserver using HTTPS

If you need to periodically update a Web server with the device location, and the polling period is sensible (e.g., every 30 minutes), your best option is to use AlarmManager and a Service. I wrote a LocationPoller which was designed for this scenario, which another developer has improved upon. Just bear in mind that it may not be possible to determine the device's location at any given moment, so you need to have a "timeout" mechanism in case you cannot find the location, since finding the location keeps the CPU (and GPS radio, where relevant) powered on. LocationPoller has such a "timeout".

Upvotes: 1

Related Questions