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

(gtxtreme123) #1

Chapter 28  Background Services


private class MyBinder extends IBinder {
public MyService getService() {
return MyService.this;
}
}


@Override
public void onBind(Intent intent) {
return new MyBinder();
}


This pattern looks exciting. It is the only place in Android that enables one Android component to
directly talk to another. However, we do not recommend it. Since services are effectively singletons,
using them this way provides no major benefits over just using a singleton instead.


Remote service binding


Binding is more useful for remote services, because they give applications in other processes the ability
to invoke methods on your service. Creating a remote service binder is an advanced topic and beyond
the scope of this book. Check out the AIDL guide in the Android documentation or the Messenger
class for more details.


For the More Curious: JobScheduler and JobServices


In this chapter, you saw how to use AlarmManager, an IntentService, and PendingIntents to put
together a periodically executing background task. In doing that, you had to do a few things manually:



  • schedule a periodic task

  • check whether that periodic task was currently running

  • check whether the network was currently up


You had to stitch a few different APIs together by hand to create one functioning background worker
that you could start and stop. It worked, but it was a lot of work.


In Android Lollipop (API 21), a new API was introduced called JobScheduler that can implement
these kinds of tasks on its own. It is also capable of more: For example, it can avoid starting up your
service at all if the network is unavailable. It can implement a “back off and retry” policy if your
request fails or restrict network access on a metered connection. You can also restrict updates so that
they only occur while the device is charging. Even where these are possible with AlarmManager and
IntentService, it is not easy.


JobScheduler allows you to define services to run particular jobs and then schedule them to run only
when particular conditions apply. Here is how it works: First, you create a subclass of JobService
to handle your job. A JobService has two methods to override: onStartJob(JobParameters) and
onStopJob(JobParameters). (Do not enter this code anywhere. It is only a sample for purposes of this
discussion.)

Free download pdf