Working with Widget Background Operations

You might think that because the App Widget doesn't run within the application process, you don't have to worry about operations taking too long. You might also think that because the App Widget is a BroadcastReceiver object, it will automatically perform its actions in the background. In both cases, you'd be wrong.

For lengthy operations, the general solution is to launch a separate thread to handle things. However, for App Widgets, this isn't feasible. Instead, you must create and launch an Android Service instance and then, from the service, you can launch a background thread. An Android service can provide two useful operations: It can provide background processing, and it can provide an interface to a remote object, such as providing access to extensions or software libraries.

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.

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.

Running services

Android keyboard 3 2MB

Process: com.and ro I d. I nputmeth od. lat I n wSl Android keyboard 00:43

Input method: touch to manage

Been There, Done That! 3.imb

Process: coiii.aiidruJdbuok.Lrluta[julĀ£22

FIGURE 18.3

The Running Services

QuizWidgetProvider$Wi00:07

Started by application: touch to stop

I Avail: 27MB+26MB In 6

Other: 26MB In 31

0 0

Post a comment