39
CHAPTER 4: Services
override fun run() {
Thread.sleep(3000)
val msg = Message.obtain()
val bundle = Bundle()
bundle.putString("MyString",
"A reply message to be sent")
msg.data = bundle
repl?.send(msg)
}
} )
thr.start()
}
}
}
The other two methods, using
a broadcast message or a
ResultReceiver
class, get handled
in Chapters
5
and
12
.
Service Subclasses
Up to now we were always using
android.app.Service
as a
base class for services we
described. There are other classes supplied by Android that are usable as base classes,
though, with different semantics. For Android 8.0, there are no less than 20 service classes
or base classes you can use. You can see them all in the Android API documentation in the
“Known Direct Subclasses” section.
Note
At
the time of writing this book, you can find this documentation at
https://developer.
android.com/reference/android/app/Service.html
.
The most important service classes are the following three:
android.app.Service
: This is the one we’ve been using so far. This
is the most basic service class. Unless you use multithreading
inside
the service class or the service is explicitly configured to execute in
another process, the service will be running inside the service caller’s
main thread. If this is the GUI thread and you don’t
expect the service
invocation to run really fast, it is strongly recommended you send
service activities to a background thread.
android.app.IntentService
: While a service by design does not
naturally handle incoming start requests
simultaneously to the
main thread, an
IntentService
uses a dedicated worker thread
to receive multiple start messages. Still, it uses just one thread to
work with start requests, so they get executed one after the other.
IntentService
classes take care
of correctly stopping services, so
you don’t need to care about this yourself. You have to provide the
service’s work to be done for each start request inside an overwritten