The UI Thread is for UI

However, there is one big limitation: in general, you cannot modify the UI from a background thread. You can only modify the UI from the main application thread.

A few widgets have special support for being updated from a background thread. ProgressBar is one in particular that is set up this way. ProgressBar is designed to let you show progress of some background work, and so the Android engineers took the time to make ProgressBar support background UI updates.

However, outside of exceptions like that, any other UI updates have to be done from the main application thread.

This is a pain.

It means that we not only have to get our slow work off of the main application thread, but we have to update the UI with the results of that work on the main application thread. This sort of inter-thread communication is annoying.

Worse, this makes configuration changes that much trickier. Suppose we start some work on a background thread, and while that work is ongoing, the user rotates the screen. Our activity and its fragments get destroyed and recreated. Somehow, we not only need to arrange for our results to get processed on the main application thread, but they also need to be processed by whatever the now-current activity and fragments are.

This has been one of the major headaches that has plagued Android app developers since Android 1.0. Countless solutions have been offered by Google and by independent developers. The current “best practices” involve:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.