Jobs run with the scheduler in the main thread. If you need a background thread, such as when you're making a network request, you need to manage that yourself. You can do this with Java Thread objects or with the AsyncTask framework. Because the code is running in a service, an AsyncTask isn't vulnerable to device configuration changes, so that would work fin—but in this demonstration, a simple thread is used.
- [Narrator] A job service runs in the main thread,…so if you want to do some work in a background thread,…you have to set it up yourself,…and when the work is done, you can communicate…with the UI with broadcast messages.…In my job service, I'll do the work using…a runnable object and a thread.…First of all, I won't be calling job finished…here in the unstart job, so I'll comment that out,…and because I'm pushing the work…to a background thread, I'll return…true instead of false.…Then here, I'll create an instance of the…runnable interface.…
I'll just name it R, and I'll instantiate it…with new runnable.…In the run method, I'll call thread.sleep,…simulating a long-running task,…then I'll surround that with try catch,…and then after the sweep is complete,…I'll move the call to job finished to here.…I'll pass in job parameters and a value of false,…meaning I don't want to reschedule.…Now notice, I've changed the job parameters object…here so that it's final, and that allows me…to reference that object from within the…
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