Книга: Beginning Android

Now, the Caveats

Now, the Caveats

Background threads, while eminently possible using the Android Handler system, are not all happiness and warm puppies. Background threads not only add complexity, but they have real-world costs in terms of available memory, CPU, and battery life.

To that end, there are a wide range of scenarios you need to account for with your background thread, including

• The possibility that users will interact with your activity’s UI while the background thread is chugging along. If the work that the background thread is doing is altered or invalidated by the user input, you will need to communicate this to the background thread. Android includes many classes in the java.util.concurrent package that will help you communicate safely with your background thread.

• The possibility that the activity will be killed off while background work is going on. For example, after starting your activity, the user might have a call come in, followed by a text message, then a need to look up a contact — all of which might be sufficient to kick your activity out of memory. Chapter 16 will cover the various events Android will take your activity through; hook the proper ones and be sure to shut down your background thread cleanly when you have the chance.

• The possibility that your user will get irritated if you chew up a lot of CPU time and battery life without giving any payback. Tactically, this means using ProgressBar or other means of letting the user know that something is happening. Strategically, this means you still need to be efficient at what you do — background threads are no panacea for sluggish or pointless code.

• The possibility that you will encounter an error during background processing. For example, if you are gathering information off the Internet, the device might lose connectivity. Alerting the user of the problem via a Notification and shutting down the background thread may be your best option.

Оглавление книги


Генерация: 1.414. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз