开发者

Finishing an AsyncTask when requested

I am creating a game where the user interacts with the GUI while the computer finds solutions to the puzzle in a background task. The user can choose to end the game any time, at which point I want to stop my background task and retrieve the solutions it found.

This is all working fine except that I can't force the background task to end when the user chooses?!? When the user selects "Done" I have the following:

computerSolutionTask.cancel(true);

// ...disable some GUI buttons etc...

w开发者_运维百科hile (computerSolutionTask.getStatus() != AsyncTask.Status.FINISHED){
   // ...do nothing...
}
txt_computer.setText(computerSolutionTask.get());

And in my AsyncTask class I am checking "isCancelled()" regularly but it just seems to hang in the while loop I included above.

I feel that I may be going about this whole thing a little incorrectly because I don't really want to cancel the background task I just want it to finish wherever it's up to and return what it has.

This thread appears to be asking the same question I am but has no solution...I'm drawing blanks with all my research thus far and any help would be much appreciated.


A running AsyncTask that is cancelled will never reach onPostExecute and so it will never 'finish'. You don't need to wait for it anyway, if your particular logic requires it use regular synchronization methods.


You need to put the condition inside the doInBackground() method to check whether the AsyncTask is cancelled or in running state.

 protected Object doInBackground(Object... x) 
    { 
        while (/* condition */)
        {

        // work...

        if (isCancelled())  break;

        } return null; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜