Android's UI thread
As mentioned in the first chapter, Android applications have a thread that is dedicated to updating the UI and also to listening to user interactions and processing the events generated by the user – like the user clicking on a menu.
Let's review the basics of Android's UI thread to guarantee that we separate the work between the UI and background threads in the best way possible.
CalledFromWrongThreadException
Android will throw a CalledFromWrongThreadException
whenever a thread that didn't create a view hierarchy tries to update its views. In practical terms, this exception will happen whenever a thread other than the UI thread updates a view. This is because the UI thread is the only one that can create view hierarchies, so it will always be the one that can update them.
It's important to guarantee that code that will update the UI is running in the UI thread. In our example, we will update a label on the UI thread after calling a service on a background thread.