Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 28  Background Services


What Services Are For


OK, we admit it: Looking at those Logcat statements was boring. But this code is really exciting!
Why? What can you do with it?


Time to go back to the Land of Make Believe, where we are no longer programmers but work in retail
shoe sales with superheroes who do our bidding.


Your Flash workers can work in two kinds of places in a store: the front of the store, where they talk to
customers, and the back of the store, where they do not. The back of the store may be larger or smaller,
depending on the store.


So far, all of your code has run in activities. Activities are your Android app’s storefront. All this code
is focused on a pleasant visual experience for your user/customer.


Services are the back end of your Android app. Things can happen there that the user never needs to
know about. Work can go on there long after the storefront has closed, when your activities are long
gone.


Enough about stores. What can you do with a service that you cannot do with an activity? Well, for
one, you can run a service while the user is occupied elsewhere.


Safe background networking


Your service is going to poll Flickr in the background. To perform networking in the background
safely, some additional code is required. Android provides the ability for a user to turn off networking
for backgrounded applications. If the user has a lot of power-hungry applications, this can be a big
performance improvement.


This does mean, however, that if you are doing networking in the background, you need to verify with
the ConnectivityManager that the network is available.


Add the code in Listing 28.4 to perform this check.

Free download pdf