By design, our service is supposed to wake up every so
often, check the online service for new status updates, and then go back to “sleep” for some time.
And this work needs to keep on happening forever, until the service is
stopped. A good way to implement this is to have our service run in a
loop and pause execution between iterations. Java provides a
that we can use to make the currently running thread pause and
relinquish CPU for some number of milliseconds.
Another consideration to keep in mind is that the service could require a good deal of time to make its connection to Twitter and pull in friends’ status data. The behavior of networking calls depends on the type of network connection we have at the moment, the responsiveness of the server, and all sorts of other factors that collectively make up the network latency.
If we run our update operation on the default thread, any delay caused by the network update will cause our user interface to block. This in turn will make our application appear sluggish to the user and may even lead to the Android system offering to kill our application by bringing up the “Force Close or Wait” dialog window, as discussed in Threading in Android.
The best solution to this problem is to put the actual work of the network update in a separate thread. To do this, we can use standard Java threading support, as shown in Example 8-5. The work of a service should often be in a separate thread from the main ...