When you use AsyncTask to run a task in the background, you have the ability to cancel the task. First, keep a reference to the task object in scope. Then, send a message to stop the task's background work with the cancel() method. Within the task, you can then check whether the task is in a cancelled state with the isCancelled() method.
- When you use AsyncTask to run a task in the background,…you have the ability to cancel the task.…First, you'll need to keep a reference…to the task object in scope.…In this application, I'll go to my Run Code Method,…and now I'm going to just work with a single task.…And I'm going to change this declaration…from a local variable, to a field.…I'll select "Refactor" and then refactor this…and then I'll extract to a field, and I'll call it "mTask".…
I'll go to the declaration…and then I'll also add a Boolean value.…It'll be private and boolean,…and I'll call it "mTaskRunning".…And I'm going to use this variable…to keep track of the task's state.…Now going back to the Run Code Method,…I'm going to wrap this bit of code…with an "if conditional" clause.…My condition will look like this:…If mTaskRunning, and mTask not equal to no.…And if that condition is true…then I'll cancel the task with "mTask.cancel"…and there's a boolean value you can pass in…named, "mayInterruptIfRunning".…
I'm going to set that to a value of true.…
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