Posts Tagged 'asynctask'  One Way to Cancel an AsyncTask  The
AsyncTask class in Android provides an easy way to do a task in
the background, without adversely impacting the main user
interface thread. Generally speaking, it works really well for
me. For a working example, refer to “Using Android AsyncTask For
Background Tasks“. Recently, however, I have had a problem in
cancelling the task.  Here’s my situation. I am working on a
game. Part of the game involves a background task that computes
moves for two players. As moves are computed, they are shown on
the app’s screen by making calls to publishProgress. The calls
occur in a loop.  while (gameNotOver) {   publishProgress
(player, move);  Back in the activity that starts the AsyncTask,
I have a call to cancel the task: “t.cancel (true)”. To break
out of the loop, I added calls to isCancelled.  if (isCancelled
()) break;  The problem arises because the UI thread’s call to
cancel does not actually stop the task. It simply sets a flag in
the AsyncTask and the