You can only communicate with the user interface from the UI, or main thread. If you try to work directly with the UI’s View objects, it’ll cause an exception. But you can send the UI messages by using a Handler object. A message contains a bundle—a collection of key-value pairs. You can create a message and send it to a particular handler, and if the handler is owned by the UI thread. It can interpret the message and take whatever action is required.
- [Narrator] You can only communicate…with the user interface in Android…from the UI or main thread.…If you try to work directly with the UI's view object,…it'll frequently cause an exception.…You'll sometimes get away with it,…but it's never a good idea.…But you can always send messages to the user interface…by using a handler object.…I showed previously how to use the handler class…to post messages to the thread's message queue.…You can also send messages from elsewhere.…
And I'll do that in this demonstration.…A message object contains a bundle.…A collection of key value pairs.…You can create a message and send it…to a particular handler, and you can send it…from the background thread to the main thread.…The handler, which is then owned by the main thread,…can interpret the message and…take whatever action is required.…My first step will be to create a handler object,…and make it a field of the main activity.…So it persists for the lifetime of the activity.…
I'll make it private to the activity,…and I'll use the handler class from Android.os,…
First, discover how to create and start simple background threads, and how to use handlers to manage a thread's message queue. Then, learn various methods for optimizing the scheduling and performance of background tasks in Android with AsyncTask, intent services, and the JobScheduler API. Plus, explore tools that help you implement multithreading for different tasks in Android: Loader, for asynchronous data loading, and the open-source API Retrofit, for making HTTP requests.
Note: To get the most out of this course, you should be comfortable programming with Java, and should understand the most basic skills that are needed to build Android apps with the Android SDK and Android Studio.
- Creating and running a background thread
- Sending messages to the UI from threads
- Managing multiple background threads
- Managing threads with AsyncTask
- Managing long-running tasks with services
- Scheduling background tasks with JobScheduler
- Using other APIs for concurrent programming