Download Teach Yourself Android Application Development in 24

Transcript
Working with Widget Background Operations
Why can’t a Thread class be used directly from an App Widget? Although the full
details are beyond the scope of this book, the simple answer is that when processing returns from the onUpdate() method, the App Widget process may go
away, destroying any running threads. An Android Service instance won’t go away,
though, so you can use it to run background operations.
315
By the
Way
You can see all the services currently running on an Android handset or emulator
by selecting Settings, Applications, Running Services. From here, you can choose to
stop services, as well. Figure 18.3 shows the Running Services screen.
FIGURE 18.3
The Running
Services
screen.
Creating a Service
A Service object is created by extending the Service class, overriding three primary
methods, and defining the service within the AndroidManifest.xml file. For the Been
There, Done That! App Widget, you must define the Service object within
QuizWidgetProvider.
onStartCommand()
Then you can move the bulk of the onUpdate() code to the
method of the Service object and create a Thread object to do the
work so the App Widget and service are responsive.