If you have multiple tasks or instances of a task to execute, you can line them up with something called a thread executor. This is part of the standard Java concurrency framework. There are other ways of doing the same thing, but the code for this is very simple. Start by creating a class that implements the Runnable interface. Put whatever code in its run() method you need to. In this case, do some logging and include a call to the sleep() method.
- [Narrator] If you have multiple tasks…or instances of a task to execute in the background,…you can line them up and execute them…simultaneously with the Thread Executor.…This is part of the standard Java concurrency package.…It isn't unique to Android and there are other ways of doing…the same thing, but the code for this is very simple.…Start by creating a class…that implements the runnable interface.…You could create it as a nested class of the current class,…but to emphasize how independent it is,…I'll create it in its own separate file.…
I'll create a new Java class and I'll name it…BackgroundTask and I'll implement the runnable interface.…When the class appears, I'll add the Run method…by using an intention action and choosing Implement Methods.…I'll get rid of these comments…and now, I have a background task class…that can be passed with thread…or as I'm going to do, to a Thread Executor.…To track what's happening in the task,…I'll create a constant names tag…that I'll use in my log get output.…
As I've done previously, I'll use a tag of CodeRunner.…
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