The code that runs in the doInBackground() method of an AsyncTask can’t communicate with the activity’s main thread. But just like with threads and handlers, there’s a way to pass information to another method that is running on the main thread. When you declare a subclass of AsyncTask, its second generic type is for progress values. The type can be a simple string, but you can also pass complex objects with multiple properties.
- [Instructor] The code that runs…in the doInBackground method of an AsyncTask…can't communicate with the activity's main thread.…But just like with threads and handlers,…there's a way to pass information…to another method that is running on the main thread.…And the AsyncTask architecture makes this even easier.…When you declare a subclass of AsyncTask…you declare three generic parameters,…types, and I've set these as strings.…The first type is the type of the parameters…that are being passed in to doInBackground.…
The second is the type of progress updates.…And the third is the type of the result…that's returned at the end of the task.…To send information to the main thread from within…doInBackground, call a method named publishProgress.…Now, to demonstrate this I'll change my for loop.…And each time I log the message doInBackground…to Logcat, I'll also call publishProgress.…The publishProgress method takes a variable array of values,…and the types of those values have to match…the second generic type that you declare in the class.…
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