Android provides a framework for managing threads and handlers, called the AsyncTask class. It does much the same thing that you do with the lower level Thread class, but makes it easy to communicate with the main thread. To use this framework, create a custom class that extends AsyncTask. You can do this in a public class or in any other top-level class, but if your goal is easy communication with the UI, it’s common to define your custom task class in the Activity class it’ll be working with.
- [Narrator] Android provides a framework…for managing threads and handlers,…named the AsyncTask class.…It does much the same thing that you would do…with lower level threads and handlers,…but it makes it very easy to communicate…with the main thread from a background task.…And, it lets you put all the code…for managing those tasks in one place.…To use this framework, create a custom class…that extends AsyncTask.…Typically, this is created as a nested class…of an activity that's going to host the task.…
Down here, I'll create a new class,…and I'll name it MyTask,…and I'll say extends AsyncTask.…When you declare the AsyncTask,…you need to pass in three types as generic declarations.…The first type is the type of parameters,…the values you pass to the task.…The second type is the type of the progress value.…Values that you pass back while the task is executing…to indicate progress in the task.…
And the third generic declaration is the type of the result.…The value you will pass back when the task is complete.…For my demonstration I'll set all three generic types…
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