Intro To Android (Workbook 2)

Services

Services are used to perform long running operations off the main thread. Services don’t have their own view. Instead they supply intents to fire when certain actions occur. Services may request starting an activity, refresh a widget or DB, or showing a notification.

You can use services in a variety of ways, but generally you can use them to batch network updates, prefetch data to keep your application data fresh, provide streaming and/or background music, and other long running tasks that users won’t need to interact directly with. In the case of something like Google Music, you provide a notification so that users are able to control the operation of the service. The actions a user can take in the notification (e.g. play or pausing a song) would file intents to open new views or simply complete the action requested.

With threading in Android, but generally speaking, all work like file I/O, network calls, and DB searches should be done off the main thread to avoid the dreaded ANR – or action not responding alert that is shown when you are taking too long to respond to a user’s request. This should be avoided at all costs, it’s just bad user experience!

Services have high priority in Android and generally won’t be killed unless there is significant need to reclaim system memory. It’s priority is second only to applications currently showing you a view.

This relies on an event driven system. After something like a data refresh finishes, you can invoke intents to update the model so that next time a particular activity is shown, you’ll have the latest.

Broadcast Recievers

A related concept is that you cannot only communicate internally through intents, but you can broadcast events across application boundaries. There are built in broadcasts, such as battery updates, network connectivity changes, and date/time changes.

You register when you are listening for particular types of events. Broadcast receivers listen for these broadcasts and take the appropriate action.